Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown Prop Warning when React.cloneElement used

I have a React component I built for a popup. PopupContent will receive a DOM element or another React component as a child.

class PopupContent extends React.Component {
    render() {
        return(
            <div>
                {React.cloneElement(this.props.children, {closePopup:this.props.closePopup})}
            </div>
        );
    }
}

The closePopup prop sets a flag to show/hide the popup

closePopup(event){
    event.preventDefault();
    this.setState({
        popupInView: false
    })  
}

The reason to pass closePopup to child is to close the popup from the child component.

This setup works well if the child is a custom React component:

<PopupContent>
    <ContentOfThePopup />
</PopupContent>

But I get the Unknown Prop Warning if the child is a DOM element.

Warning: React does not recognize the closePopup prop on a DOM element.

<PopupContent>
    <div>Content Of The Popup </div>
</PopupContent>

I could use techniques explained here to distinguish between a DOM element and a React component. But I wanted to check with the community if there is a better way

like image 965
ibex Avatar asked Oct 23 '25 16:10

ibex


1 Answers

what does this.props.children contain? Shouldn't you be iterating over it?

render() {

  return React
    .Children

    // this is the jsx version of cloneElenemnt,
    // better to use in a render function
    .map(Child => <Child.type ...Child.props ...this.props>)
}
  • Clone Element
  • React.Children.map
like image 151
Hitmands Avatar answered Oct 26 '25 04:10

Hitmands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!