Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to conditionally add props on a react component?

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?

like image 278
gpbaculio Avatar asked Oct 25 '19 06:10

gpbaculio


People also ask

Can you conditionally add attributes to components in React?

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.

Which method would you use to add attributes to components conditionally?

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.

How do you conditionally display a component in React?

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.

How do you use conditional styling in React?

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.


1 Answers

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}
  />
like image 108
Shubham Khatri Avatar answered Oct 13 '22 21:10

Shubham Khatri