Transfer component in props with children method

Viewed 402

Its possible to transfer component in props with children method?

I have to components:

 let a = (<div>
        <button onClick={TContainer.METHOD}>TuCLIK</button>
  </div>);

 <TContainer data={ restaurantList } component={a}/>

I want to call method in childen but create element in parent. I want to pass this component on props.

If its possible i dont know what writing in TContainer.METHOD to call childen method

1 Answers

You are not passing a component in your props, it's an expression.
A component should be either a class the extends React.Component or a function that returns a jsx markup.
Now when we know that components are just functions, we know that we can pass parameters to them, hence we can pass a function reference as a parameter:

let A = (onClick) => <div><button onClick={onClick}>TuCLIK</button></div>;
<TContainer data={ restaurantList } component={<A onClick={TContainer.METHOD} />}/>

Note that components should be capitalized.

Edit
As a followup to your comment, sorry but i misunderstood your question i guess.
You can't pass a reference of a method from a React component like that.

  • We can use couple of approaches regarding this scenario, one of them is to use this.props.children and pass the child component as a child.
    For example - <Parant><Child/></Parent>
  • We can pass the child component as a prop.
    For example - <Parent component={Child} /> or <Parent component={<Child />} />
  • We can write the parent component as a HOC and wrap the child with it.
    For example - Parent(Child)

In all the above examples you can't pass directly a reference of a function that is declared inside the parent's scope (as a prop to the child).
In order to pass the child a prop within the parent's internal scope you should do it inside the render method.
For example:

  render() {
    return (
      <div>
        <this.props.component onClick={this.handleClick}/>
      </div>
    );
  }

This is a snippet that demonstrate one of the examples above:

const Child = ({onClick}) => <div onClick={onClick}>Im a child, Click me!</div>

class Parent extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      counter: 0
    }

    this.addCount = this.addCount.bind(this);
  }

  addCount(){
    this.setState({counter: this.state.counter + 1});
  }

  render() {
    return (
      <div>
        <div>{`Count = ${this.state.counter}`}</div>
        <this.props.component onClick={this.addCount}/>
      </div>
    );
  }
}

const App = () => <Parent component={Child} />;

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Related