Nick Prozee Nick Prozee - 18 days ago 9
TypeScript Question

Updating one React's components state from another

I am trying to change the state of one of my components through another component. Note that I am new to reactJs



In my parents component I have a state named: _SPCommandBarDisabled

this.state = {
_SPCommandBarDisabled: true
}


In a child component (the SPSearchBox) the event is triggered that changes the state of _SPCommandBarDisabled (the log shows that the state is actually changed)

public onSearchTextChanged(newText: any) {
this.setState({ _SPCommandBarDisabled: false },
() => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) }
);


However, in my 2nd child (the SPCommandBar component) the value is not updated.


This is the code from my parents component

export default class StudentDocumentsHelper extends React.Component<IStudentDocumentsHelperProps, any> {
constructor() {
super();

this.state = {
_SPCommandBarDisabled: true
}
this.onSearchTextChanged = this.onSearchTextChanged.bind(this);
}

public render(): React.ReactElement<IStudentDocumentsHelperProps> {
return (
<div>
<SPCommandBar isDisabled={this.state._SPCommandBarDisabled} />
<SPSearchBox onTextChange={this.onSearchTextChanged} />
<SPListView />
</div>
);
}

public onSearchTextChanged(newText: any) {
this.setState({ _SPCommandBarDisabled: false },
() => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) }
);
}
}


And the SPCommandBar inherits from props

export interface ISPCommandBar {
isDisabled: boolean;
}

export class SPCommandBar extends React.Component<ISPCommandBar, any> {
constructor(props: any) {
super(props);

this.state = {
_SPCommandBarDisabled: this.props.isDisabled
};
}



Update


In my SPCommandBar component I was inheriting the _SPCommandBarDisabled prop and parsing it to the state.



In my SPCommandBar's render() method I was setting the enabled value by referring to the state:

disabled: this.state._SPCommandBarDisabled


And when updating the parents state, the child state did not seem to get updated. However, when referring to the props instead of the state it is working:

disabled: this.props.isDisabled


I wonder if I just solved my own problem or is this not the way it should be done?

Answer

EDIT after original poster found the solution:

The constructor function is only called once, when the component is created, when the props you pass to the component change, the constructor won't be called again, but rather componentWillReceiveProps, you can read more here

Original Answer:

I think the error is you are using this.props, instead of just props (which are passed on the definition of the constructor function)

Try to change this:

this.state = {
    _SPCommandBarDisabled: props.isDisabled
};