03.03 - State & Props - Send counter data through multiple components (class components)
adriangheo
Posted on November 4, 2022
src/App.js
import React from "react"
import ParentComponent from './components/ParentComponent';
import './App.css';
class App extends React.Component{
constructor(props){
super(props);
this.state = {
count: 0,
}
}
handleClick = () => {
this.setState((prevState)=>({count: prevState.count + 1}))
}
render(){
return(
<div className="App">
<h1>App.js</h1>
<button onClick={()=>{this.handleClick()}}>Click Me</button>
<ParentComponent count={this.state.count}/>
</div>
)
}
}
export default App;
src/App.css
.App{
background-color: lightskyblue;
padding: 20px 10px;
}
h1{
margin-top: 0px;
margin-bottom: 6px
}
button{
margin-bottom: 6px;
}
src/components/ParentComponent.jsx
import React from "react"
import ChildComponent from "./ChildComponent"
import "./ParentComponent.css"
class ParentComponent extends React.Component{
constructor(props){
super(props);
}
render(){
const {count} = this.props
return(
<div>
<div className="ParentComponent">
<h2>ParentComponent.jsx</h2>
<ChildComponent count={count}/>
</div>
</div>
)
}
}
export default ParentComponent
src/components/ParentComponent.css
.ParentComponent{
background-color: lightsalmon;
padding: 10px 10px;
}
h2{
margin-top: 0px;
margin-bottom: 6px
}
src/components/ChildComponent.jsx
import React from "react";
import "./ChildComponent.css"
class ChildComponent extends React.Component{
render(){
const {count} = this.props;
return (
<div className="ChildComponent">
<h3>ChildComponent.jsx</h3>
<p>The value of count is {count}.</p>
</div>
);
}
}
export default ChildComponent;
src/components/ChildComponent.css
.ChildComponent{
background-color: lightgreen;
padding: 10px 10px;
}
h3{
margin-top: 0px;
margin-bottom: 6px
}
💖 💪 🙅 🚩
adriangheo
Posted on November 4, 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