React Cheat Sheet
Run when component first loads
Use useEffect(() => ...)
to accomplish this. (useEffect docs)
import React, { useEffect } from 'react'
const MyComponent = () => {
useEffect(() => {
console.log('This ran once!')
}, []) // <--- This empty array here is important!
...
}
Set onClick Handlers
For <button>
and <a>
elements, you can use the onClick
prop to pass a function with your click handler.
const MyComponent = () => {
const onButtonClicked = () => {
console.log('Clicked!')
}
return <button onClick={onButtonClicked}>Click me</button>
}
Using <form>
const MyComponent = () => {
const onSubmit = (event) => {
event.preventDefault()
console.log(event.target.myData.value)
}
return <div>
<form onSubmit={onSubmit}>
<input name="myData" type="text" />
<input type="submit">
</form>
</div>
}
Work with arrays
const colors = [{name: 'red'}, {name: 'green'}]
const MyComponent = () => {
return <div>
{ colors.map (color => {
return <div>{color.name}</div>
})
}
</div>
}
This makes use of Array.map
which says - create a new array and for every item in the array, return a different item instead - based on the provided item.
This is the same thing as writing:
const colors = [{name: 'red'}, {name: 'green'}]
const divElements = []
for(let i = 0; i < colors.length; i++) {
divElements.push(<div>{color.name}</div>)
}
const MyComponent = () => {
return <div>{divElements}</div>
}