You will need to bind the handler to the instance of the class
.
Either do it explicit in the constructor:
constructor(props){
super(props);
this.state = {
name: 'David'
};
this.btnClick = this.btnClick.bind(this);
}
Running example of your code:
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'David'
};
this.btnClick = this.btnClick.bind(this);
}
btnClick(){
this.setState({ name: 'Sarah' });
}
render() {
return (
<div>
<button onClick={this.btnClick}>Change Name</button>
<h1>{this.state.name}</h1>
</div>
);
}
}
ReactDOM.render(<Welcome />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Or use an arrow function which use the this
reference in a lexical manner:
btnClick = () => {
this.setState({ name: 'Sarah' });
}
Running example of your code:
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'David'
};
}
btnClick = () => {
this.setState({ name: 'Sarah' });
}
render() {
return (
<div>
<button onClick={this.btnClick}>Change Name</button>
<h1>{this.state.name}</h1>
</div>
);
}
}
ReactDOM.render(<Welcome />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>