React JS-trigger event on specific state value
How can I trigger an event from the parent component when its child component state has a specific value?
For example: let's say I have a parent component and a child component where the parent state has an activeIndex property and the child state has an activeTask property.
I want to call the parent props.handleNextChild method if the active state property of the child state is 3.
How should I do it?
source to share
When the state or props of your component changes, the lifecycle method is componentDidUpdate
called after the update is complete, so you can pass handleNextChild
as a prop to your child:
class Parent extends Component {
handleNextChild() {
//do whatever
}
render() {
return (
//stuff
<Child callback={() => handleNextChild()} /> //arrow for lexical bind
//more stuff
);
}
}
and change the class of child components:
class Child extends Component {
constructor(props) {
super(props);
this.callbackHandled = false
}
// ...child class code...
componentDidUpdate() {
if (this.state.activeTask === 3) {
this.callbackHandled = false;
this.setState({ activeTask: resetValue }, () => {
if (!this.callbackHandled) {
this.callbackHandled = true;
this.props.callback();
}
});
}
render() {
// render your child component...
}
}
This will happen when your state activeTask
changes to 3. However, as long as it activeTask
remains at 3, it will run on every update, so if you want it to run only once, be sure setState
to reset activeTask
before you call callback
as I did ... I used the callback version setState
and nstance variable to ensure that the state is set before the callback is called (aka :) handleNextChild
, to avoid calling it multiple times, and to ensure that the child gets processed exactly once every time it is activeTask
set by 3.
source to share
There is no direct way to achieve this, create a callback on the parent and pass it to the child using props. Then keep checking in case the required condition is met and then calls the callback.
pseudocode:
Parent
class Parent extends Component {
handleNextChild = () => {
// parent logic comes here
}
render() {
return (
<Child handleNextChild = this.handleNextChild />
);
}
}
Child:
class Child extends Component {
onChange = () => {
if(this.state.activeTask === 3){
this.props.handleNextChild();
}
}.....
source to share
So I changed my application logic: just set the active child index to my json data and use it as state
@Statements = React.createClass
displayName: 'Statements'
getInitialState: ->
statements: @props.statements
attempt: @props.attempt
activeIndex: @props.attempt.active_statement
updateStates: (data) ->
@setState activeIndex: data.attempt.active_statement
@setState attempt: data.attempt
@setState statements: data.statements
source to share