I'm trying to practice render props patter in react but I got error of
this.props.children is not a function
this is my code
import React from 'react';
import { render } from 'react-dom';
const Box = ({color}) => (
<div>
this is box, with color of {color}
</div>
);
class ColoredBox extends React.Component {
state = { color: 'red' }
getState() {
return {
color: this.state.color
}
}
render() {
return this.props.children(this.getState())
}
}
render(<ColoredBox><Box /></ColoredBox>, document.getElementById('root'));
https://codesandbox.io/s/8z0xmk9ojl
As error says this.props.children is not a function or React Class(which is a function), instead it is an object created by invoking that function.
You can use this to fix the problem
render() {
return React.cloneElement(this.props.children, this.getState())
}
This will take the child, clone it using extra props.
Following the render props pattern, you need to have your children as a function, so you would indeed write
import React from 'react';
import { render } from 'react-dom';
const Box = ({color}) => (
<div>
this is box, with color of {color}
</div>
);
class ColoredBox extends React.Component {
state = { color: 'red' }
getState() {
return {
color: this.state.color
}
}
render() {
return this.props.children(this.getState())
}
}
render(<ColoredBox>{(color) => <Box color={color}/>}</ColoredBox>, document.getElementById('root'));
Also to make it clear, a stateless functional component is not treated the same as a function when you render it like <Box/>
However you could use the above stateless functional component like
<ColoredBox>{Box}</ColoredBox>
and it would work
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With