How to Build an SEO-Friendly React Counter
In this tutorial, we will walk through the process of building a simple counter using React. Not only will we cover the implementation, but we will also ensure that our code follows SEO best practices.
To get started, we will be using Codepen. You can begin by forking the React template pen.
In Codepen, there is no need to import React and ReactDOM as they are already included in the scope.
We will display the count in a div element and add buttons to increment the count.
1 | const Button = ({ increment }) => { |
Next, let’s add the functionality to change the count by clicking the buttons. We will achieve this by adding an onClickFunction
prop.
1 | const Button = ({ increment, onClickFunction }) => { |
Now, each Button element has two props: increment
and onClickFunction
. We create four different buttons with increment values of 1, 10, 100, and 1000.
When the button is clicked, the incrementCount
function is called. But we still need to implement the incrementCount
function to update the count.
To achieve this, we can use hooks.
1 | const { useState } = React |
In the modified code, we use useState()
to initialize the count variable to 0 and obtain the setCount()
method for updating its value.
We then utilize both in the incrementCount()
method, calling setCount()
to update the value to the existing count plus the increment passed by each Button component.
You can find the complete example code at https://codepen.io/flaviocopes/pen/QzEQPR.
tags: [“React”, “counter”, “tutorial”]