React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page.
React components are JavaScript functions that return markup(1). For example:
function MyButton() {
return (
<button>I'm a button</button>
);
}
(1) Markup is a JavaScript reactive templating system built to simplify how you build Web user interfaces using web standards with minimal enhancements to the native web APIs as possible.
<aside> ⚠️
React component names must always start with a capital letter, while HTML tags must be lowercase.
</aside>
The export JavaScript keyword makes a function accessible outside of this file. The default keyword tells other files using your code that it’s the main function in your file. Example:
export default function Square() {
return <button className="square">X</button>;
}
<button> is a JSX element. A JSX element is a combination of JavaScript code and HTML tags that describes what you’d like to display.
<aside> ⚠️
React components need to return a single JSX element and not multiple adjacent JSX elements like two buttons. To fix this you can use Fragments (<> and </>) to wrap multiple adjacent JSX elements like this:
</aside>
export default function Square() {
return (
<>
<button className="square">X</button>
<button className="square">X</button>
</>
);
}
<aside> ⚠️
To “escape into JavaScript” from JSX for a parameter, you need to add curly braces around the parameter inside the function. Example:
</aside>
function Square({ value }) {
return <button className="square">{value}</button>;
}
export default function Row() {
return (
<div className="board-row">
<Square value="1" />
<Square value="2" />
<Square value="3" />
</div>
);
}
A special function called useState that you can call from your component let it “remember” things about it state.
import { useState } from 'react';
function Square() {
const [value, setValue] = useState(null);
<aside> 💡
To collect data from multiple children, or to have two child components communicate with each other, declare the shared state in their parent component instead. The parent component can pass that state back down to the children via props. This keeps the child components in sync with each other and with their parent.
</aside>
<aside> ⚠️
State is private to a component that defines it: you have to use functions to pass a value to different components.
</aside>
To handle clicks: example to put an ‘X’ value in a square if it’s clicked: