I have already read all the stack-overflow questions related to this problem, also this official react post and the preferred solutions.
It's not recommended to use componentWillReceiveProps
anymore!
Before you mark this question as duplicate, please understand my specific question, I didn't see any solution for my specific problem.
What I'm trying to do is very simple:
I have component KInputRange
that received the value from props and send the value out (callback) onEnter event (will send the value to server only on enter)
The props.value can randomly change (coming by websocket from the server)
My Question:
Inside my components, the <input>
value attribute will get the data from props
or from state
?
If from props: How can I update the value internally when the user type input data?
If from state: How can I update the new value if the props.value has change randomly from the server?
I'm actually need to update my internal state on props change but how to do it today, if react says that's anti-pattern?
This my code so far:
class KInputRange extends React.Component<any, any> {
constructor(props: any) {
super(props);
}
private onKeyDown(e: any): void {
//If the key is enter call to props.onEnter with the current value
}
private onChange(e: any): void {
//if user change the value- change the internal value
}
public render() {
return (
<input value={?????} type="text" onChange={(e) => this.onChange(e)} onKeyDown={(e) => this.onKeyDown(e)}/>
);
}
}
Usage:
<KInputRange value={this.state.dataFromTheServer} onEnter={(val: number) => this.kInputRangeEnterClicked(val)}/>