Search code examples
reactjsreact-nativereact-hooksreact-props

I want to pass data from a child to parent REACT JS


I have a function that selects a country from a dropdown. I have put it in a file by itself. And then on my Dashboard.js I just call the funtion to appear. But how can I get the value from the Dashboard.js?

CountrySelector.js

import React, { useState, useMemo } from 'react'
import Select from 'react-select'
import countryList from 'react-select-country-list'

function CountrySelector() {
  const [value, setValue] = useState("")
  const options = useMemo(() => countryList().getData(), [])

  const changeHandler = value => {
    setValue(value)
  }

  const style = {
    display: "inline-block",
    width: "300px"
  };
  return <div style={style}><Select options={options} value={value} onChange={changeHandler} /></div>
}

export default CountrySelector;

Dashboard.js


import CountrySelector from '../util/CountrySelector';


const Dashboard = () => {
   return(
        <div>
            <CountrySelector/>
        </div>
    );
};

export default Dashboard;

I know props doesn't work because you pass data from parent to the child. And I want to pass data from child to the parent. Any help is appreciated.


Solution

  • Put your state in your parent component, and pass them as props to your child component

    import { useState, useMemo } from 'react';
    import CountrySelector from '../util/CountrySelector';
    import countryList from 'react-select-country-list';
    
    const Dashboard = () => {
      const [value, setValue] = useState('');
      const options = useMemo(() => countryList().getData(), []);
    
      return (
        <div>
          <CountrySelector value={value} setValue={setValue} options={options} />
        </div>
      );
    };
    
    export default Dashboard;
    
    import Select from 'react-select';
    
    function CountrySelector({ value, setValue, options }) {
      const style = {
        display: 'inline-block',
        width: '300px',
      };
      return (
        <div style={style}>
          <Select options={options} value={value} onChange={setValue} />
        </div>
      );
    }
    
    export default CountrySelector;