03.10 - State & Props - Send counter data to parent component (functional components)
adriangheo
Posted on December 26, 2022
src/App.js
import './App.css';
import ParentComponent from './components/ParentComponent';
function App() {
return (
<div className="App">
<p><b>App.js</b> |function|</p>
<ParentComponent/>
</div>
);
}
export default App;
src/App.css
.App{
background-color: lightskyblue;
padding: 10px 10px;
}
p{
margin-top: 6px;
margin-bottom: 12px
}
src/components/ParentComponent.jsx
import React, { useState } from "react"
import ChildComponent from "./ChildComponent"
import "./ParentComponent.css"
function ParentComponent(){
const [count, setCounter] = useState(0);
const updateCounterList = () => {
setCounter(count + 1)
}
return(
<div className="ParentComponent">
<p><b>ParentComponent.jsx</b> |function|</p>
<ChildComponent updateCounterList={()=>{updateCounterList()}}/>
<p>Click Counter value is {count}.</p>
</div>
)
}
export default ParentComponent
src/components/ParentComponent.css
.ParentComponent{
background-color: lightsalmon;
padding: 10px 10px;
margin: 10px 10px;
}
h2{
margin-top: 0px;
margin-bottom: 6px
}
src/components/ChildComponent.jsx
import React from "react";
import "./ChildComponent.css"
function ChildComponent (props) {
const handleClick = () => {
props.updateCounterList();
}
return (
<div className="ChildComponent">
<p><b>ChildComponent.jsx</b> |function|</p>
<button onClick={()=>{handleClick()}}>Add 1</button>
</div>
);
}
export default ChildComponent;
src/components/ChildComponent.css
.ChildComponent{
background-color: lightgreen;
padding: 10px 10px;
margin: 10px 10px;
}
h3{
margin-top: 0px;
margin-bottom: 6px
}
💖 💪 🙅 🚩
adriangheo
Posted on December 26, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react 03.12 - State & Props - Send color change data to parent comp (function components)
December 26, 2022
react 03.11 - State & Props - Send color change data to parent comp (class components)
December 26, 2022
react 03.10 - State & Props - Send counter data to parent component (functional components)
December 26, 2022