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.
const Button = ({ increment }) => {
return <button>+{increment}</button>
}
const App = () => {
let count = 0
return (
<div>
<Button increment={1} />
<Button increment={10} />
<Button increment={100} />
<Button increment={1000} />
<span>{count}</span>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
Next, let’s add the functionality to change the count by clicking the buttons. We will achieve this by adding an onClickFunction
prop.
const Button = ({ increment, onClickFunction }) => {
const handleClick = () => {
onClickFunction(increment)
}
return <button onClick={handleClick}>+{increment}</button>
}
const App = () => {
let count = 0
const incrementCount = increment => {
//TODO
}
return (
<div>
<Button increment={1} onClickFunction={incrementCount} />
<Button increment={10} onClickFunction={incrementCount} />
<Button increment={100} onClickFunction={incrementCount} />
<Button increment={1000} onClickFunction={incrementCount} />
<span>{count}</span>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
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.
const { useState } = React
const Button = ({ increment, onClickFunction }) => {
const handleClick = () => {
onClickFunction(increment)
}
return <button onClick={handleClick}>+{increment}</button>
}
const App = () => {
const [count, setCount] = useState(0)
const incrementCount = increment => {
setCount(count + increment)
}
return (
<div>
<Button increment={1} onClickFunction={incrementCount} />
<Button increment={10} onClickFunction={incrementCount} />
<Button increment={100} onClickFunction={incrementCount} />
<Button increment={1000} onClickFunction={incrementCount} />
<span>{count}</span>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
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.