Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

props.children in react cannot be a stateless component?

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

like image 363
Madeline Ries Avatar asked Apr 18 '18 05:04

Madeline Ries


2 Answers

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.

like image 115
Subin Sebastian Avatar answered Oct 22 '22 00:10

Subin Sebastian


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

like image 3
Shubham Khatri Avatar answered Oct 21 '22 23:10

Shubham Khatri