How to put props.children in JSX tag

Home / Uncategorized / How to put props.children in JSX tag

Question:
I have a component like this one:class Person extends React.Component {
render() {
const { language } = this.props;
return (

I speak {language}

);
}
}

And a Higher order component like this:export default (BaseComponent) =>
class extends React.Component {
render() {
return ;
}
}

I used them:class PersonList extends Component {
render() {
const NewPerson = hoc(Person)
return ;
}
}

Which was perfectly fine, it output what I wanted
I speak English

But what if I want the PersonList component to render something passed down from its parent instead of imported, like this:render(


,
document.getElementById(‘app’)
)

Now,
const NewPerson = hoc(Person)

throws an error.

I known that I can fix the HOC like this
return

{React.cloneElement(BaseComponent, { language: "English" })}

But this is a breaking change, I don’t want to do this.

Are there anyway I can archive my goal (HOC component renders something that passed down instead of imported) without breaking my HOC ?

Or there are any work around ?


Answer:
You can add a Person component created by a Higher order component this way:const NewPerson = hoc(Person)
render(


,
document.getElementById(‘app’)
)

Add {this.props.children} to your PersonList’s render function:class PersonList extends React.Component {
render() {
return(

{this.props.children}

)
}
}
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *