user3233110 user3233110 -4 years ago 62
React JSX Question

this.setState in React is not working

I'm trying to change the state of one component from another component and my state is not updating, I'm sending back the prop i want to update in my app component but this.setState doesnt work

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

import Header from './components/Header';
class App extends Component{
constructor(){
super();
this.state = {
homeLink: "Home"
}
}
onChangeLink(newLink){
this.setState({
homeLink: newLink
});
}
render(){
var user = {
name: "sadf"
}
return(
<div className="container">
<div className="row">
<Header changeLink={this.onChangeLink.bind(this)}/>
</div>
</div>
);
}
}

ReactDOM.render(
<App />,document.getElementById('app')


And here is my header component

import React, {Component} from 'react';

class Header extends Component{
constructor(){
super();
this.state = {
homeLink: 'New Link'
}
}
onChangeLink(){
this.props.changeLink(this.state.homeLink);
}
render(){
return(
<nav className="navbar navbar-default">
<button onClick={this.onChangeLink.bind(this)}>Change Link</button>
</nav>
)
}
}


export default Header

Answer Source

Try something like this:

let newPropValues = {
    root: event.target.value
};
this.setState(Object.assign({}, this.state, newPropValues));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download