I got a textbox that once the user stops typing, I want to update the results(what ever they type will be applied to an array of data and will filter down anything that does match what they type).
Right now I am using onBlur but this of course will only activate after they leave the textbox.
Would it be better to do onChange and put a timer that gets cancelled if they continue to type?
Or is there a better way.
Not sure if it makes a difference but I am reactjs
Vanilla javascript (no React)
var inputElm = document.querySelector('input');
inputElm.addEventListener('input', onInput);
function onInput(){
var duration = 1000;
clearTimeout(inputElm._timer);
inputElm._timer = setTimeout(()=>{
update(this.value);
}, duration);
}
function update(){
console.log('Do something')
}
<input>
In React you would probably do it like this:
class SomeComp extends Component {
constructor(props){
super(props);
this.state = {
inputValue: ''
}
}
onInput = (e) => {
var duration = 1000;
clearTimeout(this.inputTimer);
this.inputTimer = setTimeout(()=>{
this.updateInputValue( e.target.value );
}, duration);
}
updateInputValue = ( value )=> {
this.setState({
inputValue: value
});
}
render(){
return(
<input value={this.state.inputValue} onChange={this.onInput(evt)}/>
)
}
}
Just use onkeyup event it will fire when user releases keyboard button.
document.getElementById('inputText').onkeyup = UpdateData()
Related
I have two buttons that execute the same function, and that function needs to evaluate go backward or go forward as I show in the following image
and in the following code I want to evaluate what function next() or prev() to execute depending on which button was touched, this is built in react
const onFinish = (values) => {
if (values.users) {
const Operator = values.users.map((item) => ({
ruleAttributeName: item.ruleAttributeName,
isoAttributeId: item.isoAttributeId,
ruleOperationId: item.ruleOperationId,
mandatoryValue: item.mandatoryValue,
}));
setAttributes(Operator);
}
if (values.users) {
const attributesSave = values.users.map((item) => ({
ruleAttributeName: item.ruleAttributeName,
isoAttributeEntity: {
isoAttributeId: item.isoAttributeId,
},
ruleOperationEntity: {
ruleOperationId: item.ruleOperationId,
},
mandatoryValue: item.mandatoryValue,
}));
console.log('mandatory';
setAttributesSave(attributesSave);
setMandatoryValue();
next();
prev();
};
and in this form I pass by parameter the function
<Form
name='dynamic_form_nest_item'
onFinish={onFinish}
autoComplete='off'
>
You can identify them by assigning unique Id to both button like this
<button onClick={onFinish} Id={'1'}>Next</button>
<button onClick={onFinish} Id={'2'}>Next</button>
And in you listener check id which button clicked.
const onFinish = (event) => {
Let id = event.target.id;
if(id=== "1") {
// Do for one
} else {
// For second
}
}
I don't know the parameters that you got on that custom buttons and how is it triggering onClick event. But here is the solution for HTML buttons.
You can set a value to the button like this.
<button onClick={onFinish} value="next">Next</button>
const onFinish = (ev) => {
ev.preventDefault() // this is to prevent the refresh
const { value } = ev.target // equals with const value = ev.target.value
if(value === "next") {
next()
} else {
prev()
}
}
folks!
Does anyone know the opposite method to cellFocused in ag-grid?
I need to detect when the focused cell loses its focus and run some actions.
Thanks for your responses.
I've found a way to support onBlur event. Since ag-grid doesn't have a built-in method, I created wy own event listener to the focus cell node and remove it after losing the focus state.
So, my code looks like this. Inside the react class I have 3 additional methods:
removeCellBlurListener = () => {
const target = document.activeElement;
if (target) {
target.removeEventListener('blur', this.onCellBlur);
}
};
addCellBlurListener = () => {
const target = document.activeElement;
if (target) {
target.addEventListener('blur', this.onCellBlur);
}
};
onCellBlur = () => {
...do something on blur
};
render () {
return (
<AgGridReact
{...restProps}
onCellFocused={(e) => this.addCellBlurListener()}
onGridReady={this.onGridReady}
/>
);
}
I tried to do a checkbox that changes the text when checkbox is checked or unchecked however it seems that the state was not changed even after the checkbox is triggered. I am trying to follow a tutorial and encounter this error which for some reason can't find what is the problem. Below is my current code.
var UseOfState = class extends React.Component {
constructor(props) {
super(props);
this.state = {isCheck: true};
this.toggleCheckbox = this.toggleCheckbox.bind(this);
}
toggleCheckbox () {
console.log('checkbox triggered');
this.setState = ({isCheck: !this.state.isCheck});
}
render () {
console.log('render');
var msg;
if(this.state.isCheck) {
msg = 'checked';
console.log(this.state.isCheck);
} else {
msg = 'unchecked';
console.log(this.state.isCheck);
}
return (
<div>
<input type="checkbox" onChange={this.toggleCheckbox} defaultChecked={this.state.isCheck}/>
<h3>Check box is {msg}</h3>
</div>
);
}
}
ReactDOM.render(<UseOfState/>,document.getElementById('root'));
Here is my codepen: https://codepen.io/anon/pen/OazZpa
I want to know where is my error from there :)
There is typo on below line
this.setState = ({isCheck: !this.state.isCheck});
to
this.setState({isCheck: !this.state.isCheck});
Then it works fine.
I am trying to create a keypress listener for my React Js calculator app and when I add the event listener in, it detects additional key presses the more I press. Is there a better place to put the event listener? When I press 1234, I get
122333344444444
/****************Button Component*************/
class CalcApp extends React.Component {
state = {
value: null,
displayNumbers: '0',
selectedNumbers: [],
calculating: false,
operator:null
};
selectMath = (selectedMath) =>{
const {displayNumbers, operator,value} = this.state;
const nextValue = parseFloat(displayNumbers)
console.log(selectedMath);
/**do math and other methods*/
render() {
document.addEventListener('keydown', (event) => {
const keyName = event.key;
if(/^\d+$/.test(keyName)){
this.selectButton(keyName)
console.log(keyName);
}
});
return (
<div>
<Display displayNumbers={this.state.displayNumbers}
selectedNumbers={this.state.selectedNumbers}/>
<Button selectedNumbers={this.state.selectedNumbers}
selectButton ={this.selectButton}
selectC = {this.selectC}
displayNumbers={this.state.displayNumbers}
selectDot = {this.selectDot}
selectMath = {this.selectMath}/>
</div>
);
}
}
let domContainer = document.querySelector('#app');
ReactDOM.render(<CalcApp />, domContainer);
Remove document.addEventListener listener from render().
The method is being called whenever the components needs to re-render (changes of state / props) which attaches yet another event listener.
Suggestion: Move document.addEventListener to componentDidMount() - executed only once, and remove it via document.removeEventListener on componentWillUnmount to prevent memory leaks.
I could explain what I am trying to do, but this ReactJS example is a walkthrough of exactly what I want. The problem is I can't figure out what the equivelant would be for react native.
Basically, when I press return in the TextInput, I want the text cleared and focus maintained.
Any thoughts?
I've submitted a PR with a blurOnSubmit property.
Set it to false and the TextInput never blurs, onSubmitEditing still fires though.
Hopefully it gets merged. :)
https://github.com/facebook/react-native/pull/2149
I came out with following (working) solution:
var NameInput = React.createClass({
getInitialState() {
return {
textValue: ''
}
},
clearAndRetainFocus: function(evt, elem) {
this.setState({textValue: elem.text});
setTimeout(function() {
this.setState({textValue: this.getInitialState().textValue});
this.refs.Name.focus();
}.bind(this), 0);
},
render() {
return(
<TextInput
ref='Name'
value={this.state.textValue}
onEndEditing={this.clearAndRetainFocus} />
)
}
});
So, basically when we end editing, we will set the textValue state to the value of the TextInput and right after that (in setTimeout), we switch it back to default (empty) and retain focus on the element.
I don't know how to trigger blurOnSubmit but if you do and it works you should do that. Another thing I found that works with a functional react component in a chat application i am making is this:
... import statments
const ChatInput = props => {
const textIn = React.useRef(null) //declare ref
useEffect(()=>textIn.current.focus()) //use effect to focus after it is updated
const textInputChanged = (text) =>{
props.contentChanged(text);
}
const submitChat = () =>{
const txt = props.content.trim()
txt.length >0 ? props.sendChat(txt, props.username) : null;
}
const keyPressEvent = (e) =>{
return e.key == 'Enter'? submitChat() : null;
}
return (
<TextInput
style={styles.textInput}
keyboardType={props.keyboardType}
autoCapitalize={props.autoCapitalize}
autoCorrect={props.autoCorrect}
secureTextEntry={props.secureTextEntry}
value={props.content}
onChangeText={textInputChanged}
onKeyPress={keyPressEvent}
autoFocus={true} //i don't think you need this since we are using useEffect
ref={textIn} //make it so this is the ref
/>
)}
... export default react-redux connect stuff
if you have more inputs you can probably do some sort of ref choosing logic in the useEffect hook
this is the article that helped me figure it out, it's almost the same thing:
https://howtocreateapps.com/how-to-set-focus-on-an-input-element-in-react-using-hooks/