How to Conditionally Add Attributes to Objects

Publikováno: 16.10.2020

JavaScript is full of tricks that you don’t know you want until you … want … them. Or maybe just until you see them. One trick I recently realized was conditionally adding attributes to React elements. Of course this trick essentially boils down to conditionally adding properties to an Object, but let’s not dive too […]

The post How to Conditionally Add Attributes to Objects appeared first on David Walsh Blog.

Celý článek

JavaScript is full of tricks that you don’t know you want until you … want … them. Or maybe just until you see them. One trick I recently realized was conditionally adding attributes to React elements. Of course this trick essentially boils down to conditionally adding properties to an Object, but let’s not dive too far into specificities — let’s jump into the code.

To conditionally add properties to an object, we’ll use a conditional and destructuring:

const someObj = { prop3: 'Arsenal!' };
const obj = {
  prop1: "value1",
  prop2: "value2",
  ...(someObj ?? {})
}

And to conditionally add these properties to a React component, you could do:

<MyComponent
  prop1="value1"
  prop2="value2"
  ...(someObj ?? {})
/>

In many cases, it doesn’t matter if you have extra keys (and their values) on your objects, but if you run a tight ship with dictionary objects or use Object.keys, you’ll want to use this technique.

Have any other Object tricks? Please share them!

The post How to Conditionally Add Attributes to Objects appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace