this.props.children
In React, props.children refers to the child elements or components that are passed to a React component as its children. This feature enables a React component to both access and manipulate the content contained within it.
Consider this example:
<MyComponent>
<p>Hi, This is w3wiki!</p>
<h5>This is some more content in w3wiki</h5>
</MyComponent>
Here, <p> and <h5> tags are children of <MyComponent>.
Example: The example demonstrates a Button component using props.className and props.children, allowing flexible rendering of customized content for each button in the App component.
Javascript
// App.js import React from "react" ; import "./App.css" ; const Button = (props) => { return ( <button className={props.className}> {props.children} </button> ); }; function App() { return ( <div> <Button className= "primary" > GFG-primary! </Button> <Button className= "secondary" > <span>GFG-secondary!</span> </Button> </div> ); } export default App; |
CSS
/* App.css*/ .App-header { background-color : #282c34 ; min-height : 100 vh; display : flex; flex- direction : column; align-items: center ; justify- content : center ; font-size : calc( 10px + 2 vmin); color : white ; } .primary { padding : 12px ; margin : 3px ; cursor : pointer ; } .secondary { padding : 12px ; } |
Output:
Difference between React.cloneElement and this.props.children
React.cloneElement and this.props.children are functionalities within React that play distinct roles in manipulating React components and elements. Although both are employed for this purpose, they are utilized in different contexts. Let’s delve into the specifics of each.
Table of Content
- React.cloneElement()
- this.props.children
- Difference between React.cloneElement and this.props.children.