DEV Community

adriangheo
adriangheo

Posted on

03.04 - State & Props - Send counter data through multiple components (functional components)

App preview:
The way the app will look like

Project files:
An image of project file structure


src/App.js

import React, {useState} from "react"
import './App.css';
import ParentComponent from './components/ParentComponent';


const App = () => {
  const [count, setCount] = useState(0);

  return(
    <div className="App">
      <h1>App.js</h1>
      <button onClick={()=>{setCount(count+1)}}>Click Me</button>
      <ParentComponent count={count}/>
    </div>
  )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

src/App.css

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

h1{
  margin-top: 0px; 
  margin-bottom: 6px 
}

button{
  margin-bottom: 6px; 
}
Enter fullscreen mode Exit fullscreen mode


src/components/ParentComponent.jsx

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

const ParentComponent = (props) => {
    const {count} = props;

    return(
        <div className="ParentComponent">
            <h2>ParentComponent.jsx</h2>
            <ChildComponent count={count}/>
        </div>
    )
}

export default ParentComponent
Enter fullscreen mode Exit fullscreen mode

src/components/ParentComponent.css

.ParentComponent{
    background-color: lightsalmon;
    padding: 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"

const 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: 10px 10px;
}

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

Top comments (0)