TamarG TamarG - 1 month ago 14
React JSX Question

Add custom props to a custom component

I've built my own custom react-bootstrap Popover component:

export default class MyPopover extends Component {
// ...
render() {
return (
<Popover {...this.props} >
// ....
</Popover>
);
}
}


The component is rendered like so:

// ... my different class ...

render() {

const popoverExample = (
<MyPopover id="my-first-popover" title="My Title">
my text
</MyPopover >
);

return (
<OverlayTrigger trigger="click" placement="top" overlay={popoverExample}>
<Button>Click Me</Button>
</OverlayTrigger>
);
}


Now, I want to add custom props to
MyPopover
component like that:

my text

And to use the new props to set some things in the popover
for example -

<Popover {...this.props} className={this.getClassName()}>
{this.showTheRightText(this.props)}
</Popover>


but then I get this warning in the browser:


Warning: Unknown props
popoverType
on tag. Remove these props from the element.


Now, I guess that I can just remove the
{...this.props}
part and insert all the original props one by one without the custom props, but In this way I lose the "fade" effect and also it's an ugly way to handle this problem. Is there an easier way to do it?

Answer

The easiest solution here is to simply remove the extra prop before sending it to the Popover component, and there's a convenient solution for doing that.

export default class MyPopover extends Component {
  // ...
  render() {
    let newProps = Object.assign({}, this.props);  //shallow copy the props
    delete newProps.popoverType;  //remove the "illegal" prop from our copy.

    return (
        <Popover {...newProps} >
           // ....
        </Popover>
    );
  }
}

Obviously you can (and probably should) create that variable outside your render() function as well.

Basically you can send any props you want to your own component, but you'd have to "clean" it before passing it through. All react-bootstrap components are cleansed from "illegal" props before being passed as attributes to the DOM, however it doesn't handle any custom props that you may have provided, hence why you have to do your own bit of housekeeping.

React started throwing this warning as of version 15.2.0. Here's what the documentation says about this:

The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.

[...]

To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component.

For further reading, check this page from the official react site.

Comments