Home > Mobile >  react - how to extract props to share
react - how to extract props to share

Time:03-23

Let's assume I have 2 inputs below, which share the same value of props except className

    <ReactCardFlip>
      <input
        type="text"
        maxLength={1}
        className={inputStyles.input}
        defaultValue={value}
      />
      <input
        type="text"
        maxLength={1}
        className={`${inputStyles.input} ${inputFlipClass}`}
        defaultValue={value}
      />
    </ReactCardFlip>

Apart from creating new component, is it possible to share the props like

    <ReactCardFlip>
      <input
        {...inputProps}
        className={inputStyles.input}
      />
      <input
        {...inputProps}
        className={`${inputStyles.input} ${inputFlipClass}`}
      />
    </ReactCardFlip>

?

CodePudding user response:

Yes you can. You can also create a props getter (a term coined by Kent C Dodds) for the input


const getInputProps = (config) => ({
  type: "text",
  maxLength: 1,
  defaultValue: value,
  ...config,
})


return (
  <ReactCardFlip>
    <input
      {...getInputProps({ className: inputStyles.input })}
    />
    <input
      {...getInputProps({ 
        className: `${inputStyles.input} ${inputFlipClass}` 
      })}
    />
  </ReactCardFlip>
);
  • Related