The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Conditionally add a HTML attribute in React

posted on 14.1.2023 by Below Surface in "React"

Let's say we have the following code:

const currentCategory = "React";
const categories = ["Node.js", "React", "Next.js"];
return (
  <select>
      {
        categories.map((category, index) => (
          <option key={index} value={category} selected={category == currentCategory}>{category}</option>
        )
     }
  </select>
)

React will loop through the categories array and add an option element for each entry (Node.js, React and Next.js). Also, for each element, it will check if the current category string matches the string of currentCategory, which is "React" in every iteration. Of course, two times the result will be false, one time it will return the boolean "true". Only in this case, the "selected" attribute will be added to the option element.

The output will look like this:

<select>
  <option key="0" value="Node.js">Node.js</option> 
  <option key="1" value="React" selected>React</option> 
  <option key="2" value="Next.js">Next.js</option> 
</select>

Tags:

react
next.js
html
attribute

More posts of this category

How to pass variables down to child components

Work with props in React/Next.js with TypeScript

React

An easy and elegant way to change a boolean useState value

How to toggle a useState boolean value easily

React

Scroll to the page top after rendering a React component

Fix the annoying SPA issue and scroll to the top!

React

How I fixed the auto scroll bug of ReactQuill

Quill is a nice WYSIWYG text editor, but had a weird scroll bug

React