I am trying to use a custom component as an input field in react-select. Since I need validation I am trying to use HTML5 oninvalid
(onInvalid
in JSX) for my input tag and set the custom message for oninvalid
. However I am unable to pass the message as a prop to the component that I am setting in select. Below is my code.
Input.js
import React from "react";
import { components } from "react-select";
export default class Input extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("component mounted");
}
setInvalidMessage = event => {
event.target.setCustomValidity("Custom Message");
};
render() {
if (this.props.isHidden) {
return <components.Input {...this.props} />;
}
return (
<components.Input
{...this.props}
required
onInvalid={this.setInvalidMessage}
/>
);
}
}
example.js
import React from "react";
import Input from "./Input";
import Select from "react-select";
import { colourOptions } from "./docs/data";
const InputBoxWithText = props => {
return <Input {...props} />;
};
export default () => (
<form>
<Select
closeMenuOnSelect={true}
components={{ InputBoxWithText }}
options={colourOptions}
/>
<input type="submit" />
</form>
);
If I pass Input in components attribute I get the hard coded message in Input.js. If I pass InputBoxWithText I don't see Input mounting at all.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Example from './example';
ReactDOM.render(
<Example />,
document.getElementById('root')
);
Here is CodeSandBox.io URL.
Can any one let me know if what am I doing wrong.
Not sure if you already found a solution but I managed to pass my custom props using an arrow function
<Select
closeMenuOnSelect={true}
options={colourOptions}
components={{
Input: (inputProps: InputProps) => (
<components.Input {...inputProps} />
),
}}
/>
It's better to pass custom props via select:
props.selectProps
To avoid re-creating of Custom component each time Select updates, what may cause unexpected bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With