Let's Dive into React (Pt. 4)
Tags: react, javascript, beginners, webdev
Published: 2021-06-11 20:31:25

Let's continue from where we [stopped](https://dev.to/shafspecs/let-s-dive-into-react-pt-3-2647) in the last article, wherein we created a component and returned our first HTML element using JSX.

Our goal is to build a counter and a thing to note is, a component can range from a HTML tag to an entire webpage. Let's try and think of the 'components' or different parts of our counter-app.

First, we have the background and that's where everything will be located. Secondly, we have a counter that shows the current count we are on. Thirdly, we have a button to increase the count of the number displayed by one. Lastly, another button to decrease the count number by one.That's a simple breakdown of our counter app that we will be making. Let's begin.

Our `App` component will be our main component for this project, remember, we have a header at the top, then the numbers, then the buttons.

Let's start with the header, ```JSX
import React from 'react'

const App = () => {
    return (
        <div>
            <header>Counter App</header>
        </div>
    )
}

export default App
```

We have our header created in the div, let's create the count component. Remember, we can add an HTML tag, some JavaScript and keep writing, but let's make it another component to keep our code clean and short. Let's create a folder called `components` to store all our other components. Inside, we create the file `Counter.jsx`
![component folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfnrn1otwwqiwtzfut9w.png)

Let's create a function called `Counter` after importing React and return a `div` ```JSX
import React from 'react'

const Counter = () => {
    return (
        <div>
            
        </div>
    )
}

export default Counter
```

Let's just add a `<h3>` tag with 0 as its value, we will come back to add functionality. But, we must first import it into our `App.jsx` to render it on the page.```JSX
import React from 'react'
import Counter from './components/Counter'

const App = () => {
    return (
        <div>
            <header>Counter App</header>
            <Counter />
        </div>
    )
}

export default App
```
![Good counter added](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7at8eg8bwqag19c5nnbu.png)

Let's add a button component the same way we added the counter, except instead of `<h3>` tag, we will use `<button>` tag. And import it into our `App.jsx` component.
Our `App.jsx`:```JSX
import React from 'react'
import Counter from './components/Counter'
import Button from './components/Button'

const App = () => {
    return (
        <div>
            <header>Counter App</header>
            <Counter />
            <Button />
        </div>
    )
}

export default App
```
and our page:
![Our new page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nd01w5gywz442obg0q1o.png)

OK, we have done quite a lot, we have added our components, rendered them through `index.jsx` and will now explain how to control the update of our counter number.

*Note:* **React elements are immutable. Once you create an element, you can’t change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.**

This is a problem, it means if we want to change counter, each time we click we re-render the page. That would be very inconvenient, cause that means for example, if we have a form with verification, we will refresh the page every time a value is inputted. That's where states come in?

**A state is a JavaScript object that is managed within a component (similar to variables declared within a function), and influences the output of a component. There is no need for re-rendering at all, it's just like a variable that changes value within a function that can change value while the function is running, without need to re-call the function.**

How do we create a state and change it? First, we import the (non-default) function `useState` from the `react` module in the `App.jsx`. (**Make sure it is written between curly braces**)
![Line 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c2efvfxzop22brnjw35s.png)

Next, we use array destructuring to initialize our state. This is the general syntax of `useState`:```JSX
const [nameOfVariable, functionToUpdateVariable] = useState(defaultValueOfVariable)
```
> *The `useState` is always written outside the return method*

*Note:* **The default value of a state can be a string, number, array, boolean or even object.**

Let's create ours and call it `count` and the function to update `setCount`.```JSX
const [count, setCount] = useState(0)
```
Let's now set the `Counter` component to be `count` and the default value to be the `useState` default.

But, the `count` variable and the `Counter` are in 2 different files. How will we connect them? The answer is 'Component Properties' or called `props` for short.

**In short, props are objects that transfer data between a parent component and it's child component and vice-versa. What is a parent and child component? A parent component is the one that imports a component while the child component is the one being exported.**

Let's transfer the count to the `Counter` component. The way props are moved between a parent and it's child is:
```JSX
//Parent component
function Parent () {
  const name = 'John'
  const age = 22

  return(
    <Child nameProp={name} ageProp={age}/>
  ) 
}

//Child Component
function Child (props) {
  return(
    <h1>My name is {props.nameProp}</h1>
    <h3>His age is {props.ageProp}</h3>
  )
}
```

Let's dissect what's above, we have two variables, `name` and `age` (Props can be **any** data and datatype, not just states). And we want to display them in our child component. In our parent component, we give them a custom name (any name literally), and set it to the data we want to pass. Notice the variables written in curly braces.

*Note:* **Any JavaScript written in JSX's HTML is written between curly braces, i.e written in the `return` function.**

In the child component, we accept the `props` argument.  Recall we called `props` an object, and the values of the object are what we set in the parent component. So, we get each prop we passed, and using the rule above, wrote the props in curly braces.

Let's see how that will look in our *own* code.
```JSX
//App.jsx
...
<Counter count={count}/>
...

//Counter.jsx
...
const Counter = (props) => {
  return(
    <h3>{props.count}</h3>
  )
}
...
```

We passed `count` to `Counter` above with the name `count`(name it whatever you like. This is **your** own project), accepted it, and displayed it.
![Our state](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt8381ryzsmbok8eupxb.png)

Now, if you change the default value of the state and save, it will automatically change in the browser. In the next article, we will learn how to use the button to change numbers and make the way we write our `props` shorter. See you in the next article.