React is a library which takes functions which return JSX, evaluates them, and updates the DOM with the result.
We call a function which returns JSX a component.
const Banana = () => <p>Banana</p> // Just a function that returns some JSX
Above we've defined a Banana
component. const
s containing Components always start with capital letters, otherwise it won't work.
We can use our Banana
component like this with JSX:
<Banana />
// React renders <p>Banana</p> on the screen
<Banana />
is a special syntax for calling the function we defined above. <Banana />
is a bit like saying: Banana()
One way to think of React is that it allows us to define our own custom HTML tags e.g. Now we have: <div />
, <input />
and <Banana />
Once you've defined a component, you can reuse it inside other components.
const FruitBowl = () => <Banana /> // reuses Banana component
<FruitBowl />
// Renders <p>Banana</p> on the screen
In order to get react setup in your project there is a little bit of code needed. Usually when you work in a React project this has already been done for you. But just in case you come across it, here is how it works:
index.html
:
<html>
<head>
<script src="/index.js"></script>
</head>
<body>
<div id="root">
</div>
</body>
</html>
index.js
:
const Banana = () => <p>Banana</p>
const rootDiv = document.querySelector('#root')
ReactDOM.render(<Banana />, rootDiv)
Once your javascript code has run, the DOM will look like this:
<html>
<head>
<script src="/index.js"></script>
</head>
<body>
<div id="root">
<p>Banana</p>
</div>
</body>
</html>
ReactDOM.render(
will likely only be used once in your project, and will probably only be configured for you, so don't worry too much about this.