Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally add attributes to React components?

Is there a way to only add attributes to a React component if a certain condition is met?

I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since readOnly="false" is not the same as omitting the attribute completely.

The example below should explain what I want, but it doesn't work.

(Parse Error: Unexpected identifier)

function MyInput({isRequired}) {   return <input classname="foo" {isRequired ? "required" : ""} /> } 
like image 323
Remi Sture Avatar asked Jul 01 '15 14:07

Remi Sture


People also ask

How do you add HTML attribute dynamically in React?

By using spread attributes, you can dynamically add (or override) whatever attributes you'd like by using a javascript object instance. In my example above, the code creates a disabled key (with a disabled value in this case) when the disabled property is passed to the Hello component instance.

How do you add an attribute to an element in React?

To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref . Copied!

How do you add an if else condition in JSX?

We can embed any JavaScript expression in JSX by wrapping it in curly braces. But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.


2 Answers

juandemarco's answer is usually correct, but here is another option.

Build an object how you like:

var inputProps = {   value: 'foo',   onChange: this.handleChange };  if (condition)   inputProps.disabled = true; 

Render with spread, optionally passing other props also.

<input     value="this is overridden by inputProps"     {...inputProps}     onChange={overridesInputProps}  /> 
like image 41
Brigand Avatar answered Sep 22 '22 03:09

Brigand


Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:

const InputComponent = function() {     const required = true;     const disabled = false;      return (         <input type="text" disabled={disabled} required={required} />     ); } 

will result in:

<input type="text" required> 

Update: if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30 and 167 of the DOMProperty.js file.

like image 128
Gian Marco Toso Avatar answered Sep 20 '22 03:09

Gian Marco Toso