0

Should be simple, but for some reason, I cannot figure out this one. I just want a value defined in the Parent to be usable by the Child, but delivering the variable does not seem to work.

    function Parent(props) {
      const name='Jimmy';
      props.foo = name;
      return props.children;
    }
    
    function Child(props) {
      const result = props.foo;
      return <h1>hello, {result}</h1>
    }
    
    export default function App() {
      return (
        <div className="App">
          <Parent>
            <Child foo={this.props} />
          </Parent>
        </div>
      );
    }
  • It is helpful to include information about what you have attempted in-order to solve the question – Vuk Oct 06 '22 at 21:50

1 Answers1

0

I just want a value defined by the Parent to be usable by the Child.

  • You are setting the foo property of an object and then returning the children property. How will that other property foo be available in the returning context?

  • {this.props} refers to the props of App, not Parent.

Solution:

When passing values or closures from parent to child component, we can use 3 options.

  • Context API
    • Use when children can be deep down from parent component
  • Pass props to children
    • Use for immediate parent-child context sharing
  • Composition
    • Use children as function & pass the relevant object

This accommodated example follows Composition.

function Parent(props) {
  const name='Jimmy';
  return props.children(name);
}

function Child(props) {
  const result = props.foo;
  return <h1>hello, {result}</h1>
}

export function App(props) {
  return (
      <div className="App">
          <Parent>
             {(name) => {
                return (
                   <Child foo={name} />
                )
            }}
          </Parent>
      </div>
  );
}

Further readings:

tanmoy
  • 1,276
  • 1
  • 10
  • 28
  • Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. – Arifur Rahaman Oct 06 '22 at 03:49
  • 1
    Kindly run this snippet in `https://playcode.io/react` and let me know the result. I only tested there. So, far, the context of this question and answer do not concern with export, imports, or anything else. Developers should accommodate as needed. – tanmoy Oct 06 '22 at 04:03