This React cheat sheet is for my students who attend the three days React crash course. The React cheat sheet may be used and or copied by anyone.
// Import React and ReactDOM.
import React from 'react'
import ReactDOM from 'react-dom'
// Render component into the DOM.
ReactDOM.render(
<h1>Hello, World!</h1>,
document.getElementById('root')
)
// Stateless component.
const Title = () => {
return <h1>React Crash Course Cheat Sheet</h1>
}
// Stateless component that receives properties.
const Description = (props) => {
return <p>In the upcoming three days you will learn the basics of react, {props.name}.</p>
}
// Component can only return one element.
const Introduction = () => {
return (
<section>
<Title />
<Description name="Peter"/>
</section>
)
}
Find more information about components and props on the React documentation page.
// use classes to create a component with state.
import { Component } from 'react'
class App extends Component {
constructor(props) {
super(props)
this.state = {date: new Date()}
}
render() {
return (
<p>
Today it is {this.state.date.toLocaleTimeString()}.
</p>
)
}
}
Each component has several "lifecycle methods" that you can override to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens.
componentWillMount() {
// method is called immediately before the initial render
}
componentDidMount() {
// method is called immediately after the initial render
}
componentWillReceiveProps() {
// method is called when component is receiving new props
}
shouldComponentUpdate() {
// method is called before rendering with new props or state
}
componentWillUpdate() {
// method is called immediately before rendering
}
componentDidUpdate() {
// method is called immediately after rendering
}
componentWillUnmount() {
// method is called immediately before component is unmounted from DOM
}
Find more information about component lifcycle on the React documentation page.
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.
render() {
const {isLoggedIn, username} = this.state
return (
<div className={`${isLoggedIn ? 'login' : 'logout'}`}>
{isLoggedIn ? <p>Logged in as {username}.</p> : <p>Logged out.</p>}
</div>
)
}