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?
You can use any logic and conditionals in order to build the object. You will most commonly use the ternary operator to add conditional attributes to an element in React.
Spread Operator This method is one of my favorites when it comes to conditional props. The Spread Operator is used when passing all the properties of an object or all the elements of an array to a React Component. Here, I have used the attributes object to store all the required attributes of the input field.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. This example renders a different greeting depending on the value of isLoggedIn prop.
Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code). Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.
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}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With