In the last articles 1 and 2, we setup our project and did a little chit-chat about what was actually happening. But now, let's start writing code. In this project, we will be making a counter that has a button to increase the count and another to decrease the count.
Let's explain this code we wrote above.
import React from 'react'
In the code above, we imported React library from our
node_modules folder (you can head there yourself, and you will see a folder named
react), this is necessary and will be imported on every page we write some React code.
import ReactDOM from 'react-dom`
Using this code above, we imported React-DOM into the file, this is necessary in our entry-level file only (in our case,
index.jsx), and we will use it to render our page.
Rendering is simply the act of showing what we wrote in our React file on the browser.
Finally, we called the
render() function to give us our webpage. This method takes 2 parameters, the first is what to render, and the second is where to render. We chose to render
Hello React and to render it in the
<div> element with id:
ReactDOM.render('Hello React', document.getElementById('root'))
Let's edit our code, it's possible for us to write our code below line 2 and just render it at the end, but what if it's a site? full of pages and several links? Our code will be long and that's inconvenient.
That's the first thing, now I want you to import 'React' from it's module (no answers shown yet, refer above for a hint). Let's create a component.
App component, let's create a function called
App. Can be arrow function or a normal function, doesn't matter.
Our function will have a return method in it, Let's create a
<div> tag and write 'Hello World' in it. Feel free to add a tag in the
<div> and write more things. And this brings up another important rule, your return function can return only one thing, in our case, one
We can save our code and run
npm run start but wait, we can still see 'Hello React'. That's because
index.jsx is our entry point and since we haven't linked it to our
App.jsx, we still see our old code.
We don't need to add
.jsx into our file, Snowpack tool automatically handles that (only for JS files, if CSS or other, we add the extension). In our first parameter, let's set our App as the rendered thing. First we remove the ;Hello React' message, then we write what we imported (
App) like we are writing HTML (in between the tag symbol, < >). Like below
Allow me to add something here, and that's the fact that any tag without a closing tag e.g
<br> tag must have the
/ at the end i.e
<br/>, just typing
<br> is wrong. So there we have it, save that and run it.
Voila! We now have hello world written there. In the next article, we will actually start building the counter app and adding CSS. Feel free to add, change or do whatever. If you want a greater challenge, create a new component entirely and import it into the
App.jsx, display it from there like we did in
index.jsx and keep having fun.