score:300
What even is ‘children’?
The React docs say that you can use
props.children
on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.My simple explanation of what
this.props.children
does is that it is used to display whatever you include between the opening and closing tags when invoking a component.A simple example:
Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no
this
keyword so just useprops.children
const Picture = (props) => {
return (
<div>
<img src={props.src}/>
{props.children}
</div>
)
}
This component contains an
<img>
that is receiving someprops
and then it is displaying{props.children}
.Whenever this component is invoked
{props.children}
will also be displayed and this is just a reference to what is between the opening and closing tags of the component.
//App.js
render () {
return (
<div className='container'>
<Picture key={picture.id} src={picture.src}>
//what is placed here is passed as props.children
</Picture>
</div>
)
}
Instead of invoking the component with a self-closing tag
<Picture />
if you invoke it will full opening and closing tags<Picture> </Picture>
you can then place more code between it.This de-couples the
<Picture>
component from its content and makes it more reusable.
Reference: A quick intro to React’s props.children
score:0
Children is a reserved name, and the value of this special children prop will always be the content between the opening and closing tags of your custom component. So in this case, this content between the opening and closing tag, that is what will be available on props children inside of that component.
score:6
This is answered, but wanted to add an optimization example. You can decompose inline to only get specific properties instead of the entire props object (which means you don't have to keep writing props
).
const MyView = ({title, children}) => {
return (
<>
<h1>{title}</h1>
{children}
</>
);
}
Then you'd use it like so:
import { MyView } from './MyView';
const MyParentView = () => {
return (
<MyView title="Hello">
<h2>World</h2>
</MyView>
);
}
The end result would be HTML which renders out to something like this:
<div>
<h1>Hello</h1>
<h2>World</h2>
</div>
score:33
props.children
represents the content between the opening and the closing tags when invoking/rendering a component:
const Foo = props => (
<div>
<p>I'm {Foo.name}</p>
<p>abc is: {props.abc}</p>
<p>I have {props.children.length} children.</p>
<p>They are: {props.children}.</p>
<p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
</div>
);
const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;
invoke/call/render Foo
:
<Foo abc={123}>
<Baz />
<Bar />
</Foo>
score:36
I assume you're seeing this in a React component's render
method, like this (edit: your edited question does indeed show that):
class Example extends React.Component {
render() {
return <div>
<div>Children ({this.props.children.length}):</div>
{this.props.children}
</div>;
}
}
class Widget extends React.Component {
render() {
return <div>
<div>First <code>Example</code>:</div>
<Example>
<div>1</div>
<div>2</div>
<div>3</div>
</Example>
<div>Second <code>Example</code> with different children:</div>
<Example>
<div>A</div>
<div>B</div>
</Example>
</div>;
}
}
ReactDOM.render(
<Widget/>,
document.getElementById("root")
);
<div id="root"></div>
<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>
children
is a special property of React components which contains any child elements defined within the component, e.g. the divs
inside Example
above. {this.props.children}
includes those children in the rendered result.
...what are the situations to use the same
You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.
Source: stackoverflow.com
Related Query
- What is {this.props.children} and when you should use it?
- React functional stateless component, PureComponent, Component; what are the differences and when should we use what?
- When should you use render and shallow in Enzyme / React tests?
- You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react
- I want to put the images in an object or array and use them when I need them. What should I do?
- What does this error means? Render methods should be a pure function of props and state
- When should you NOT use React memo?
- What is the difference between .ts and .tsx extensions. Both are used as extensions for typescript files in react. So where should we use them?
- Should you ever use this.setState() when using redux?
- Should I wrap every prop with useCallback or useMemo, when to use this hooks?
- Warning: You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored
- When should I use Redux Saga instead of Redux Thunk, and when should I use Redux Thunk instead of Redux Saga?
- In React JS, when should you use a store vs directly manipulating the view's state?
- Passing an object as Meta/Tag when extending a class. What is this syntax and what does it do?
- In a React Component, what's the difference between foo(){} and bar = () => {} and when should I use which?
- What should I use instead of document.queryselector() when using React?
- REACT: What I should write in propTypes when in form I use input type="file'?
- What Type should I use for TypeScript props with children?
- When importing from a library, Invariant failed: You should not use <Route> outside a <Router>
- React: When to use functions as children and when to use components
- When to use Props and when State in Preact sub components
- What is the different between classes prop in mui and className prop when you insert style in to them?
- When and where should I use a "fetchingData" state for normalized data in Redux store?
- What happens when you use defaultProps when using redux with react?
- When you want to change User's data, should you delete the jwt and create a new one for the session?
- React Router: props aren't passed down when directly accessing the URL of child component. Will I need to use the same state in both parent and child?
- what is making props behavior inconsistent when set as a variable and passed into another function
- Render methods should be a pure function of props and state. But i just use function parameter
- React - how to pass component and props to children component and make that component use that props
- Error: Invariant failed: You should not use <Link> outside a <Router> when I try to test my app using localhost
More Query from same tag
- write SVG text from keyboard
- How to call function of another component in react
- unable to solve input field issue while entering the values using reactjs
- React datepicker cutting calendar on mobile screen
- Node JS - Posting HTML form (or FormData) from my Node server to a 3rd party server
- Installing create-react-app gives npm ERR! shasum check failed and npm ERR! Unexpected end of JSON input while parsing near '...mojOzGIEI2rg0m24Yb5Oq'
- Validate antd form input in onChange with the value return by back-end API call
- Generate dynamic PDF with React
- react-router -> Create route without shared HTML from AppComponent
- Axios sends a post to the duplicate url
- Importing initialisation functions in ReactJS / React-Native
- How to Async/Await using useEffect for fetching data?
- How to fix warning "function -- makes the dependencies of useEffect Hook change on every render"?
- else statement is ignored in react
- React + Redux: proper way to handle after-dispatch logic
- How to change background color in paragraph depending on the value in reactjs
- CSS changes when navigating from and back to Page - React
- How to fill users variable with data from GET request in React
- React, update component after async function set
- How can I properly change the title of react-bootstrap DropdownButton on click?
- How to implement simple notifications in drf + react?
- Webpack Unexpected token <
- react redux firebase error while importing firebase, not able to import firebase. how to solve it?
- How to add custom label to clicked Marker using react-google-maps libary?
- i want to show a different image when button is clicked
- I want to use embedded Browser inside of my WebPage in React
- Get Mongoose validation error message in React
- React scroll to top animation button does not work
- Can't hide a DIV with React
- How to disable right click for a react bootstrap card?