Another way of using JavaScript to control your rendered view is to tie the elements that are rendered to a condition. When the condition is true, one view renders. When it's false, it's a different view. We can do this with the basic if/else statement.
FreeCodeCamp has a class MyComponent which contains a boolean in its state which tracks whether you watn to display some element in the UI or not. The button toggles the state of this value. Right now, it render the same UI everytime. Let's rewrite the render() method with an if/else statement so that if display is true, you return the current markup.
Otherwise, return the markup without the h1 element.
Code:
classMyComponentextendsReact.Component{constructor(props){super(props);this.state={display:true}this.toggleDisplay=this.toggleDisplay.bind(this);}toggleDisplay(){this.setState((state)=>({display:!state.display}));}render(){// Change code below this linereturn(<div><buttononClick={this.toggleDisplay}>Toggle Display</button><h1>Displayed!</h1></div>);}};
You can also use the && logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is true, and if it is, return some markup.
If the condition is true, the markup will be returned. If the condition is false, the operation will immediately return false after evaluating the condition and return nothing. You can include these statements directly in your JSX and string multiple conditions together by writing && after each one.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)