Reputation: 759
I have the following React component:
class Parent extends Component {
constructor(props) {
super(props)
this.state = {
isRendered: false
}
}
render() {
return (
<div className="result">
Rendering result
</div>
)
}
}
Based on the state of this.state.isRendered
, I want my <div>
component to render if the state is true
, and not render if the state is false
.
What would be the best way to organize it in React?
Upvotes: 1
Views: 197
Reputation: 111
You can use simple conditional ternary operator to do this:
condition ? if_true_result : if_false_result
Your code should be like this:
render() {
const {isRendered} = this.state;
return isRendered ?
<div className="result">
Rendering result
</div>
: ''
}
Another official way is following the guidelines about Conditional Rendering in Reactjs document: https://reactjs.org/docs/conditional-rendering.html
Upvotes: 1
Reputation: 2720
Just check this.state.isRendered
in the render
. Here I used a simple AND check. Click on the button to change state and see how it works (snippet takes a short while to run):
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
isRendered: false
}
}
render() {
const {
isRendered
} = this.state;
return (
<div>
{isRendered &&
<div className="result">
Rendering result
</div>
}
<button onClick={() => {this.setState({isRendered: !isRendered})}}>{isRendered? 'Hide' : 'Show'}</button>
</div>
)
}
}
ReactDOM.render(<Parent />, document.getElementById('app'))
<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="app"></div>
Upvotes: 3
Reputation: 6743
There are many ways to accomplish that
{ this.state.isRendered ?
<div className="result">
This if the isRendered is true
</div>
: <div className="result">
This if the isRendered is false
</div> }
Upvotes: 0
Reputation: 1816
You are allowed to return null
or false
for React components. So, if you don't want anything to get rendered, you could do the following:
...
render() {
if (!this.state.isRendered) return null
return (
<div className="result">
Rendering result
</div>
)
}
or, alternatively
...
render() {
return this.state.isRendered && (
<div className="result">
Rendering result
</div>
)
}
Upvotes: 1
Reputation: 6737
Using a ternary operator check whether isRendered is true else return null:
class Parent extends Component {
constructor(props) {
super(props)
this.state = {
isRendered: false
}
}
render() {
return (
<div>
{this.state.isRendered ?
<div className="result">
Rendering result
</div> : null
}
</div>
)
}
}
Upvotes: 1