1

As the question state, what I am trying to do is pass a child value from child to parent. I want to call the child variable in my parent function.

Parent code

function App() {

  let [value, setVal] = useState(null);
  ...
  const onLayoutChange = (layout) => {
    console.log(value);
    if (value != null) {
      value.resize();
    }
    //   chartInstance.resize();
  };

  return (
    <ResponsiveGridLayout
      layouts={layout}
      onLayoutChange={() => onLayoutChange(layout)}
    >
      <div key="1">
        <Card style={styles} val={setVal} />
      </div>
    </ResponsiveGridLayout>
  );
}

#1 child code

export default function SimpleCard(props) {
 
  return (
    <Card style={props.style.main}>
      <CardContent>
        <NewvsReturnVisitors value={props.val} />
      </CardContent>
    </Card>
  );
}

#2 child code

const Newvsresturnvisitors = (props) => {
  ...
  let [val, setVal] = useState(null);

  let chartInstance = null;
  props.value(val);

  function renderChart() {
    const renderInstance = echarts.getInstanceByDom(chart.current);

    if (renderInstance) {
      chartInstance = renderInstance;
      setVal(chartInstance);
    } else {
      chartInstance = echarts.init(chart.current, null, {
        width: 500,
        height: 300
      });

      setVal(chartInstance);
      // chartInstance.resize();
    }
    chartInstance.setOption(option);
  }
  ...
}
export default Newvsresturnvisitors;

I am not sure if this is possible, any advice is really appreciated.

This is the link to my codesandbox

yongchang
  • 503
  • 6
  • 18
  • 1
    Does this answer your question? [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – DBS Sep 10 '21 at 08:50

2 Answers2

2

You can create a state variable in the parent component, and then pass the setXXX method to the child component, in the child component call the setXXX method to pass the variable to the parent.

The KNVB
  • 3,588
  • 3
  • 29
  • 54
  • i have edit my question, so i have tried ur method, but now i have a new warning. `Warning: Cannot update a component (App) while rendering..` same link, open console and the warning is there – yongchang Sep 10 '21 at 09:52
  • You may try to move console.log(value); out of the onLayoutChange function. – The KNVB Sep 10 '21 at 09:57
  • I have edit my question , so i encapsulate the value with a if condition and my the resize function is not executed :( – yongchang Sep 10 '21 at 10:10
0
const changeLayout = (layout) => {
    //   chartInstance.resize();
  };


<ResponsiveGridLayout
      layouts={layout}
      onLayoutChange={changeLayout}
    >

try to use props li like this

Kofusu
  • 164
  • 1
  • 10