Search code examples
javascriptreactjstypesflow-js

Change passable prop to a function to simplify them


I have this code that contain props

const Dropdown = (props: Props): React.Node => {
  const {
    name, isDisable, onChange, placeholder, value, data
  } = props;

  return (
    <Select
      onChange={onChange}
      defaultValue={valueDefiner(value)}
      styles={SelectStyle}
      placeholder={placeholder}
      name={name}
      options={data}
      isDisabled={isDisable}
    />
  );
};

it's took 3 line for only props

I have assignment to change the props into a function to simplified them, so I can import them as a function and only take 1 line for props


Solution

  • You can use an object notation to pass the props where key and value are the same string.

    Whatever other props are extra or changed you can write them later and even override them.

    const Dropdown = (props: Props): React.Node => {
    
    
      return (
        <Select {...props} isDisabled={props.isDisable}
          defaultValue={valueDefiner(props.value)}
          styles={SelectStyle}
          options={props.data}
        />
      );
    };
    
    

    Another way is to destructure these props in the function definition line itself.

    const Dropdown = ({
        name, isDisable, onChange, placeholder, value, data
      }: Props): React.Node => {
    
      return (
        <Select
          onChange={onChange}
          defaultValue={valueDefiner(value)}
          styles={SelectStyle}
          placeholder={placeholder}
          name={name}
          options={data}
          isDisabled={isDisable}
        />
      );
    };