Unable to pass values from child component to parent component

Viewed 29

App.js

import React,{useState} from 'react';
import Header from './components/header'
import './css/main.css'

const App = ()=>{
  const [color, setColor] = useState('red');
  const fun = (color)=>{
    console.log(color)
    setColor(color)
  }
  return(<Header colorMethod={fun} color={"slategrey"}/>);
}

export default App;

header.js

import React from 'react';

const Header = (props)=>{
    const myStyle = {
    header:{
        background : 'lightslategrey',
        padding: "10px",
        fontFamily: "Sans-Serif",
        display:'grid',
        gridGap:'20px'
    },
    button:{
        background :'slateblue',
        color :'whitesmoke'
    }
  };
    return(
    <header style={myStyle.header}>
        This is a {props.name} and it is generally the {props.color} component that we see.
        <button style={myStyle.button} onClick={()=>{
            props.colorMethod(props.color)
        }}>Change</button>
    </header>
    );
}

export default Header;

When I click the button in the header, I get the console log however, the color is not changed.I need to build something where the props are exchanged between multiple componets.

2 Answers

The color don't change because you're passing slategrey as props to Header. If you want Header to always have the latest color state you should pass Header color={color} ... />

Header.js

import React, { useState } from 'react';

const Header = (props) => {
    const [color, setColor] = useState('slateblue');
    const myStyle = {
        header: {
            background: 'lightslategrey',
            padding: "10px",
            fontFamily: "Sans-Serif",
            display: 'grid',
            gridGap: '20px'
        },
        button: {
            background: color,
            color: 'whitesmoke'
        }
    };
    const onHandleClick = () => {
        props.colorMethod(props.color)
        setColor(props.color);
    }
    return (
        <header style={myStyle.header}>
            This is a {props.name} and it is generally the {props.color} component that we see.
            <button style={myStyle.button} onClick={() => onHandleClick()}>Change</button>
        </header>
    );
}

export default Header;

App.js

import React, { useState } from 'react';
import Header from './components/header'

const App = () => {
  const [color, setColor] = useState('red');
  const fun = (color) => {
    console.log(color)
    setColor(color)
  }
  return (<Header colorMethod={fun} color={color} />);
}

export default App;
Related