Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props to custom components in react-select

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.

like image 999
Sachin Kumar Avatar asked Sep 28 '18 08:09

Sachin Kumar


2 Answers

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} />
    ),
  }}    
/>
like image 73
Emma Avatar answered Oct 10 '22 09:10

Emma


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.

like image 26
MADfly Avatar answered Oct 10 '22 09:10

MADfly