How to pass props to custom components in react-select

↘锁芯ラ 提交于 2020-08-10 04:46:47

问题


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.


回答1:


I don't have the solution (i'm looking for the same thing as well), but you example has multiple errors.

To load the input you have to write components={{ Input: InputBoxWithText }}, since the component name for Input is not InputBoxWithText.

Also the onInvalid does not seem to be part of the Input API, so it will never trigger. Are you trying to use the <input oninvalid="" />..?




回答2:


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.




回答3:


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} />
    ),
  }}    
/>


来源:https://stackoverflow.com/questions/52551786/how-to-pass-props-to-custom-components-in-react-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!