Learn the fundamentals of React, including simple and class components, state, props, and submitting form data.
Conditional rendering
<div id="root"></div> |
function WarningBanner(props) { | |
return !props.warn ? null : ( | |
<div className="warning"> | |
Warning! | |
</div> | |
); | |
} | |
class Page extends React.Component { | |
constructor(props) { | |
super(props); | |
this.handleToggleClick = this.handleToggleClick.bind(this); | |
this.state = { | |
showWarning: false | |
}; | |
} | |
handleToggleClick() { | |
this.setState(state => ({ | |
showWarning : !state.showWarning | |
})); | |
} | |
render() { | |
return ( | |
<div> | |
<WarningBanner warn={this.state.showWarning} /> | |
<button onClick={this.handleToggleClick}> | |
{this.state.showWarning ? "Hide" : "Show"} | |
</button> | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<Page />, | |
document.getElementById("root") | |
); |
<script src="https://unpkg.com/react/umd/react.development.js"></script> | |
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> |
* { | |
font-family: sans-serif; | |
margin: 0; | |
} | |
button { | |
height: 40px; | |
width: 200px; | |
} | |
.warning { | |
background-color: red; | |
text-align: center; | |
width: 100%; | |
padding: 10px; | |
font-size: 14pt; | |
color: white; | |
} |