03.02 - State & Props - Send counter data to child component (functional components)

adriangheo

adriangheo

Posted on November 4, 2022

03.02 - State & Props - Send counter data to child component (functional components)

App preview:
The way the app will look like

Project files:
An image of project file structure


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

function App(){
  return(
    <div className="App">
      <h1>App.js</h1>
      <ParentComponent/>
    </div>
  )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

src/App.css

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

h1, h2, h3{
  margin-top: 0px; 
  margin-bottom: 6px;
  padding-top: 0px;
  padding-bottom: 0px;

}
Enter fullscreen mode Exit fullscreen mode


src/components/ParentComponent.jsx

import React, { useState } from "react";
import ChildComponent from "./ChildComponent"
import "./ParentComponent.css"

function ParentComponent(){
    const [counter, handleClick] = useState(0);

    return (
      <div className="ParentComponent">
        <h2>ParentComponent.jsx</h2>
        <button onClick={()=>(handleClick(counter+1))}>Click me</button>
        <br/><br/>
        <ChildComponent count={counter}/>
      </div>
    );
  }

export default ParentComponent;
Enter fullscreen mode Exit fullscreen mode

src/components/ParentComponent.css

.ParentComponent{
    background-color: lightcoral;
    padding: 15px 10px;
  }
Enter fullscreen mode Exit fullscreen mode


src/components/ChildComponent.jsx

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

function ChildComponent(props){
    const {count} = props;

    return(
        <div className="ChildComponent">
            <h3>ChildComponent.jsx</h3>
            <p>The value of count is {count}.</p>
        </div>
    )
}

export default ChildComponent;
Enter fullscreen mode Exit fullscreen mode

src/components/ChildComponent.css

.ChildComponent {
    background-color: lightgreen;
    padding: 15px 10px;
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
adriangheo
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