JSX is not HTML
JSX is not understood by browsers. If you try to execute the buttonv function in a regular browser console.
function Button (props) {
return React.createElement(
"button",
{ type: "submit" },
props.label
);
}ReactDOM.render(
React.createElement(Button, { label: "Save"}),
mountNode
);
components using classes
React supports creating components through the JavaScript class syntax as well.
class Button extends React.Component {
render() {
return (
<button>{this.props.label}</button>
);
}
}
ReactDOM.render(<Button label="Save" />, mountNode);
exactly are hooks
A hook in a React component is a call to a special function. All hooks functions begin with the word
const Button = () => {
let count = 0; return (
<button>{count}</button>
);
};ReactDOM.render(<Button />, mountNode);
user events
You can add an event handler with an “onEvent” property (to the button element in this case
const Button = () => {
let count = 0; return (
<button onClick={() => console.log('Button clicked')}>
{count}
</button>
);
};ReactDOM.render(<Button />, mountNode);
updating state
to track state updates and trigger virtual DOM diffing and real DOM reconciliation
const [count, setCount] = React.useState(0);
multiple components
The new Display component will be a purely presentational one with no state or interactions of its own.
const Display = (props) => (
<pre>COUNT VALUE HERE...</pre>
);
sibling components
We now have two elements to render: button and display. We can’t render them directly next to each other like this:
ReactDOM.render(<Button /><Display />, mountNode);
components reusable
Components are all about reusability. Let’s make the button component reusable by changing it so that it can increment the global count with any value, not just 1.
const CountManager = () => {
// .. return (
<Button clickAction={incrementCounter} />
<Button clickAction={incrementCounter} />
<Button clickAction={incrementCounter} />
<Display count={count} />
);
};
Adding new props
We can change the render method pass the values we want to test with to this new prop.
return (
<div>
<Button clickAction={incrementCounter} clickValue={1} />
<Button clickAction={incrementCounter} clickValue={5} />
<Button clickAction={incrementCounter} clickValue={10} />
<Display content={count} />
</div>
)
side effects
Side effects usually need to happen either before or after React’s render task
useEffect(() => {
// Do something after each render
// but only if dep1 or dep2 changed
}, [dep1, dep2]);