DEV Community

adriangheo
adriangheo

Posted on

03.09 - State & Props - Send counter data to parent component (class components)

App preview:
The way the app will look like

Project files:
An image of project file structure


src/App.js:

import React from "react";
import './App.css';
import ParentComponent from "./components/ParentComponent";

class App extends React.Component{

  render(){
    return(
      <div className="App">
        <p><b>App.js</b> |class|</p>
        <ParentComponent/>
      </div>
    )
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

src/App.css

.App{
  background-color: lightskyblue;
  padding: 10px 10px;
}

p{
  margin-top: 6px; 
  margin-bottom: 12px 
}
Enter fullscreen mode Exit fullscreen mode


src/components/ParentComponent.jsx

import React from "react"
import ChildComponent from "./ChildComponent"
import "./ParentComponent.css"

class ParentComponent extends React.Component{
    constructor(){
        super();
        this.state = {
          count: 0
        }
    }

    updateCounterList(){
        this.setState((prevState)=>({count: prevState.count+1}))
    }

    render(){
        return(
            <div className="ParentComponent">
                <p><b>ParentComponent.jsx</b> |class|</p>
                <ChildComponent updateCounterList={()=>{this.updateCounterList()}}/>
                <p>Click Counter value is {this.state.count}.</p>
            </div>
        )
    }

}

export default ParentComponent
Enter fullscreen mode Exit fullscreen mode

src/components/ParentComponent.css

.ParentComponent{
    background-color: lightsalmon;
    padding: 10px 10px;
    margin: 10px 10px;
}

h2{
    margin-top: 0px; 
    margin-bottom: 6px 
}
Enter fullscreen mode Exit fullscreen mode


src/components/ChildComponent.jsx

import React from "react";
import "./ChildComponent.css"


class ChildComponent extends React.Component{
    constructor(props){
        super(props);
    }

    handleClick = () => {
        this.props.updateCounterList();
    }


    render(){
        return (
            <div className="ChildComponent">
                <p><b>ChildComponent.jsx</b> |class|</p>
                <button onClick={()=>{this.handleClick()}}>Add 1</button>
            </div>
        );
    }
}

export default ChildComponent;
Enter fullscreen mode Exit fullscreen mode

src/components/ChildComponent.css

.ChildComponent{
    background-color: lightgreen;
    padding: 10px 10px;
    margin: 10px 10px;
}

h3{
    margin-top: 0px; 
    margin-bottom: 6px 
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)