Passing props to this.props.children in React
In this tutorial, we are going to learn about how to pass the props to
this.props.children
in react.
In react this.props.children
is used to pass the data(components,elements) between opening and closing jsx
tags.
Consider we have the two Components Child
and App
where we need to pass the logMe
method to all its child components.
import React,{Component} from 'react';
const Child = (props)=>{
return (
<div>
<h1>Child {props.index}</h1> <button onClick={()=>props.logMe()}>Log</button> </div>
)
}
class App extends Component{
logMe =()=>{ console.log('Hii child') }
render(){
return (
<div className="App">
{this.props.children} </div>
)}
}
ReactDOM.render(
<App> <Child/> <Child/> </App>,document.getElementById('root')
);
In general, we can pass the logMe
method to Child
components by using props but in our case, we are using this.props.children
so that we didn’t have a direct way to pass the data.
React.Children.map and React.cloneElement
React offers us two methods React.Children.map and React.cloneElement by using these methods we can iterate over each children and clone the each react element with our props.
Let’s update our code by using these two methods.
import React, { Component } from "react";
import ReactDOM from "react-dom";
const Child = props => {
return (
<div>
<h1>Child {props.index}</h1> <button onClick={() => props.logMe()}>Log</button> </div>
);
};
class App extends Component {
logMe = () => {
console.log("Hii child");
};
render() {
const updateChildrenWithProps = React.Children.map( this.props.children, (child, i) => { return React.cloneElement(child, { //this properties are available as a props in child components logMe: this.logMe, index: i }); } );
return <div className="App">{updateChildrenWithProps}</div>; }
}
ReactDOM.render(
<App>
<Child />
<Child />
</App>,
document.getElementById("root")
);
In the above code, we passed logMe
method, index
property to all child components by using the React.cloneElement
.
Output :