DEV Community

Cover image for Let's Dive into React (Pt. 4)
Abdur-Rahman
Abdur-Rahman

Posted on

Let's Dive into React (Pt. 4)

Let's continue from where we stopped 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,

import React from 'react'

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

export default App
Enter fullscreen mode Exit fullscreen mode

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

Let's create a function called Counter after importing React and return a div

import React from 'react'

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

        </div>
    )
}

export default Counter
Enter fullscreen mode Exit fullscreen mode

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.

import React from 'react'
import Counter from './components/Counter'

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

export default App
Enter fullscreen mode Exit fullscreen mode

Good counter added

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:

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
Enter fullscreen mode Exit fullscreen mode

and our page:
Our new page

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

Next, we use array destructuring to initialize our state. This is the general syntax of useState:

const [nameOfVariable, functionToUpdateVariable] = useState(defaultValueOfVariable)
Enter fullscreen mode Exit fullscreen mode

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.

const [count, setCount] = useState(0)
Enter fullscreen mode Exit fullscreen mode

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:

//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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

//App.jsx
...
<Counter count={count}/>
...

//Counter.jsx
...
const Counter = (props) => {
  return(
    <h3>{props.count}</h3>
  )
}
...
Enter fullscreen mode Exit fullscreen mode

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

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.

Top comments (0)