I often find myself in the situation of needing to make a component accept any valid HTML property to make the underlying HTML element use them.
class Input extends React.Component {
// Here I use one of the `props` to add logic to
// my component
onChange = () => alert(this.props.alert);
render() {
// Here I want to pass all the properties
// down to the HTML input element
return <input onChange={this.onChange} {...this.props} />
}
}
My above example will throw a warning because React complains about the alert
property not being a valid one for input
.
I usually workaround the problem doing as follows:
class Input extends React.Component {
// Here I use one of the `props` to add logic to
// my component
onChange = () => alert(this.props.alert);
render() {
const {
alert, // eslint-disable-line no-unused-vars
...props
} = this.props;
// Here I want to pass all the properties
// down to the HTML input element
return <input onChange={this.onChange} {...props} />
}
}
Now the component works properly but I don't feel comfortable with the end result.
I understand why React doesn't allow to pass unknown properties to its primitives, since they are not going to use them and it's not clean to provide useless properties that in the future may become valid HTML properties or lead to misbehaviors or side effects.
But I don't understand how React suggests to handle this (pretty common) use case.
Is there any suggested way to handle this case in a clean manner?