Täglich Shaarli

Alle Links eines Tag auf einer Seite.

May 10, 2021

javascript - How to pass props to {this.props.children} - Stack Overflow
thumbnail
const Child = ({ doSomething, value }) => (
  <button onClick={() => doSomething(value)}>Click Me</button>
);

class Parent extends React.Component{
  doSomething = value => {
    console.log("doSomething called by child with value:", value);
  }

  render() {
    const childrenWithProps = React.Children.map(this.props.children, child => {
      // checking isValidElement is the safe way and avoids a typescript error too
      if (React.isValidElement(child)) {
        return React.cloneElement(child, { doSomething: this.doSomething });
      }
      return child;
    });

    return <div>{childrenWithProps}</div>;
  }
}

function App() {
  return (
    <Parent>
      <Child value={1} />
      <Child value={2} />
    </Parent>
  );
}

ReactDOM.render(<App />, document.getElementById("container"));