1

I have a function component (A) import another function component (B).

B has a onChange value, I want to get the onChange value all the time when I import B in A.

I have no idea how to get it.

Here is the code like this:

A:

import B from './B';

const A = () => {
  // I want to get B's onChange value over here
  return (
    <B />
  );
}

B:

import React, { useState } from 'react';

const B = () => {
  const [value, setValue] = useState('');

  return (
    <SomePicker value={value} onChange={(value) => setValue(value)}
  );
} 
Morton
  • 5,380
  • 18
  • 63
  • 118
  • 1
    Data flow is unidirectional in React. So you cannot use the state from a child component in its parent component. – yudhiesh Oct 27 '20 at 04:42
  • https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs This one answers you question! – Tom Sep 27 '22 at 17:24

1 Answers1

1

You can refer below solution.

import B from './B';

const A = () => {
 const getOnChangeValueFromB = (data) => {
   console.log(data)// you will get onChange value here
  };   
  // I want to get B's onChange value over here
  return (
    <B callBack={getOnChangeValueFromB}/>
  );
}

import React, { useState } from 'react';

const B = (props) => {
  const [value, setValue] = useState('');
const returnValueToA = (value) => {
    setValue(value)
    props.callBack(value);

  }
  return (
    <SomePicker value={value} onChange={(value) => returnValueToA(value)}
  );
} 
Maheshvirus
  • 6,749
  • 2
  • 38
  • 40