7

I want to conditionally add props on an input type, I want to check if input_key is a number and if it is, I want to add min_max props, cause I don't want it added if it's of any type

 const min_max = {
   min: 0,
   max: 100
 };
 <Input
    type={type}
    name={input_key}
    id={input_key}
    {input_key === 'number' && ...min_max}
    required={required}
    placeholder={placeholder}
  />

how do I make it work by using spread like that?

5 Answers 5

7

You can make use of ternary condition

<Input
    type={type}
    name={input_key}
    id={input_key}
    {...(input_key === 'number'? min_max: {})}
    required={required}
    placeholder={placeholder}
  />
Sign up to request clarification or add additional context in comments.

Comments

3

Simply have a condition and use spread syntax.

// sample prop
let input_props = {
  type,
  name: input_key,
  id: input_key,
}

// condition to add min_max as prop.
if (input_key === 'number') {
  input_props = {
    ...input_props,
    ...min_max              // include min_max 
  }
}

return (
  <Input
    {...input_props}        // spread syntax to pass all input_props
    required={required}
    placeholder={placeholder}
  />
)

Comments

1

I think you can do this if you have min and max prop to your input as

 <Input
type={type}
name={input_key}
id={input_key}
max={inputKey === 'number' ? min_max.max : ''} 
min={inputKey === 'number' ? min_max.min : ''} 
required={required}
placeholder={placeholder}
/>

Hope it helps

Comments

0

Nothing special

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }


  render() {
    const min_max = {
      max : 10,
      min : 1
    }
    
    const j = false;
  
    return (
      <div>
       <input type="number" { ...(j && min_max || {})} />
      </div>
    );
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Comments

0

You can make it into a function

  const getNumberInputProps = (inputKey, otherProps) => {
    if (inputKey === "number")
        return otherProps
    return {}
}

then you can call it and spread the output like this

 <Input
  type={type}
  name={input_key}
  id={input_key}
  {...getNumberInputProps(input_key, min_max)}
  required={required}
  placeholder={placeholder}
/>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.