Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add attributes to react DOM element

I have a scenario where I'm using React.js to create a div using the following code :

React.createElement('div', {}, "div content") 

Some additional javascript processing will allow me afterwards to deduce if this div needs to have the className attribute set to" ClassA" or "ClassB" or if it shouldn't have className at all.

Is there a way in javascript to access the div that was created from the React DOM and to add to it the className attribute?

Note : I couldn't achieve this is JSX so I resorted to the createElement method.

Edit: it is worth to mention that i might need to conditionally add attributes other than className. For example, I might need to add to an anchor tag an "alt" attribute or not based on conditional logic. Thank you in advance.

like image 420
jojo Avatar asked Oct 14 '16 05:10

jojo


People also ask

How do you conditionally load component in React?

lazy() to render components conditionally. You can use the React. lazy() function conditionally to ensure a component is rendered only if it is needed.

How do you add data attribute 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!

Should you use ternary or && operator to conditionally render React components?

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. When condition evaluates to true, the operator returns “This is True”; otherwise (when condition is falsy) it returns “This is False”.


1 Answers

Use JSX spread. Build and object with props, modify it however you like and pass it to component like so:

const props = {
    name: 'SomeName'
}

if (true) {
    props.otherName = 'otherName';
}

return (
    <SomeComponent {...props}/>
);

See that ... syntax? That spread operator do the job - all props will end up as separate attributes on your component.

Take a look at this plunk: http://www.webpackbin.com/4JzKuJ9C-

like image 82
Alexander Doroshenko Avatar answered Oct 31 '22 01:10

Alexander Doroshenko