0

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.

  • This question was answered a hundred times before ;) https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs – PRSHL Nov 09 '22 at 10:06
  • in short: define the state in the parent and pass the `state` and the `setState` function as props to the child. then use both values from the props inside the child element – PRSHL Nov 09 '22 at 10:07

1 Answers1

2

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;

Kevin Yobeth
  • 939
  • 1
  • 8
  • 17