Ram Kumar
Ram Kumar

Reputation: 848

Receive params from child component functions

I have 2 components parent and child in separate .js files and I'm trying to get the value of the select component in the child from the parent.

Child component

export default function ChildComponent(props) {

  return (
    <Select value="0" onChange={(event) => props.onClick(event.target.value)}>
      <MenuItem value={0}>Edit</MenuItem>
      <MenuItem value={1}>Save</MenuItem>
    </Select>
  );

}

Parent component which renders Child components

import ChildComponent from './ChildComponent';

  function alertValue(param) {
    alert(param);
  }

ReactDOM.render(<ChildComponent
    onClick={() => alertValue()} />, document.querySelector("#somediv"));

When the value of the select component is changed in a child, it does invoke the reset timer in parent component however the value is undefined, what am I missing here? I have seen other solutions based on class, but is it possible to do without a class?

Upvotes: 0

Views: 44

Answers (2)

Akhil Aravind
Akhil Aravind

Reputation: 6130

You passed the value from child component to props, but you are not passing it in the function in parent component. so parent component is not getting the value.

  import ChildComponent from './ChildComponent';

function alertValue(param) {
    alert(param);
    }

ReactDOM.render(<ChildComponent
    onClick={() => alertValue()} />, document.querySelector("#somediv"));

This is wrong, you are not passing params here in parent component

Change the above code to

import ChildComponent from './ChildComponent';
 function alertValue(param) {
    alert(param);
    }

ReactDOM.render(<ChildComponent
    onClick={(e) => alertValue(e)} />, document.querySelector("#somediv"));

Upvotes: 3

Tien Duong
Tien Duong

Reputation: 2595

The problem is you don't pass any value to alertValue function

<ChildComponent
    onClick={() => alertValue()} />

You need to pass value to alertValue function

<ChildComponent
    onClick={(value) => alertValue(value)} />

Upvotes: 1

Related Questions