I need to trigger a function when the value of Hidden input/textArea/TextField changing in React. Not when the user enter values. When dynamically changing the hidden input value trigger a function.
import TextField from "@material-ui/core/TextField";
class RowComponent extends Component {
constructor(props) {
super(props);
this.state = {
xx: "",
salary: 0,
};
}
handleChange = (event) => {
this.setState({
xx: event.target.value,
});
};
render() {
const {
member: { salary },
} = this.props;
console.log(this.state.xx);
return (
<TextField
name="HiddenField"
type="hidden"
value={this.state.salary !== 0 ? this.state.salary : salary}
onChange={this.handleChange}
/>
);
}
}
onChange
will not trigger here because it will only fire when the user changes the value of the input field (e.g., user types in a new character).
Based on the logic of your app, It looks like the value
of TextField
will only be controlled by the prop as long as the RowComponent
salary state is not equal to 0
(based off of this condition on your TextField
: value={this.state.salary !== 0 ? this.state.salary : salary}
) - and this is evident and is much more clear when you browse the state/props with React Dev Tools.
So, what you can do is compare the previous props & state with the current ones & assess whether or not to update the state xx
componentDidUpdate(prevProps, prevState) {
if (prevProps.member.salary !== this.props.member.salary) {
if (this.state.salary === 0) {
this.setState(
{
xx: this.props.member.salary
},
() => {
console.log("new xx", this.state.xx);
}
);
}
}
if (prevState.salary !== this.state.salary) {
this.setState(
{
xx: this.state.salary
},
() => {
console.log("new xx", this.state.xx);
}
);
}
}