-
Notifications
You must be signed in to change notification settings - Fork 0
React Tips
For a formal introduction to React, read the official tutorial in the React documentation.
- React: a popular framework for frontend development.
- JSX: a special kind of JavaScript for writing HTML/CSS/JS components.
- Component: a single part of a React application that can be rendered.
- Props: attributes needed to render a React component.
- State: representation of information in a React component, the component re-renders when state changes.
Use JSX to define elements.
In addition to HTML elements, you can include custom React elements, in this case, MyComponent
is a custom element.
A JSX element should contain just one HTML element, but you can create multiple HTML elements by wrapping them in an empty "fragment" which looks like: <></>
.
const el = (
<>
<h1>Page Title</h1>
<p>This page is written in JSX.</p>
<MyComponent />
</>
)
You can also include CSS and JS in JSX markup:
function doClick() {
alert('You clicked me!')
}
const el = (
<>
<h1 style={{color: 'red'}}>Page Title</h1>
<p>This page is written in JSX.</p>
<MyComponent />
<button onClick={doClick}>
</>
)
A React component can be defined as a function that returns JSX.
You can use curly braces {}
to insert the value of a variable into the JSX.
function MyComponent(props) {
return <p>Hello, {props.name}!</p>
}
Props can be passed to a component like so:
<MyComponent name="Andrea" />
You can loop over a list of values and render one element for each of them.
Specify a key that is unique for each element.
const fruits = ['apple', 'banana', 'coconut']
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
)
State allows you to keep track of information inside a component and then re-render the component when the state is updated. A component "reacts" to state changes.
import { useState } from 'react'
function Counter() {
const [ count, setCount ] = useState(0)
return (
<>
<p>Current Count: {count}</p>
<button onClick={() => setCount(prev => prev + 1)}>Increase</button>
<button onClick={() => setCount(prev => prev - 1)}>Decrease</button>
</>
)
}