React - toggle in stateless component
You can't tell React to re-render the UI by assigning new value directly to the variable (in your case you did isPanelOpen = !isPanelOpen
).
The correct method is to use setState
.
But you cannot do it in a stateless component, you must do it in a stateful component, so your code should looks like this
import React, {Component} from 'react';
class playerInfo extends Component {
constructor(props){
super(props);
this.state = {
isPanelOpen: false
}
}
render() {
return (
<div onClick={() => this.setState({isPanelOpen: !this.state.isPanelOpen})}>Toggle</div>
{this.state.isPanelOpen && <div className="info-panel">
{this.props.children}
</div>}
);
}
}
Explanation
Remember two things:
1) Your UI should only bind to this.state.XXXX
(for stateful component) or props.XXX
(for stateless component).
2) The only way to update UI is by calling setState()
method, no other way will trigger React to re-render the UI.
But... how do I update stateless component since it doesn't have the setState
method?
ONE ANSWER:The stateless component should be contained in another stateful component.
ExampleLet's say your stateless component is called Kid
, and you have another stateful component called Mum
.
import React, {Component} from 'react';
class Mum extends Component {
constructor(props){
super(props);
this.state = {
isHappy: false
}
}
render() {
return (
<div>
<button onClick={() => this.setState({isHappy: true})}>Eat</button>
<Kid isHappy={this.state.isHappy}/>
</div>
);
}
}
const Kid = (props) => (props.isHappy ? <span>I'm happy</span> : <span>I'm sad</span>);