Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add HTML property conditionally in React

I'm trying to add a aria-current condition in React just if my path variable is null.

{props.path.map((values, index) => {
  const path = values.path ? `/${values.path}` : null;
  const aria = path !== null ? `aria-current="page"` : null;

  return (
    <li 
      className="breadcrumb-item"
      {...aria}
    >
      {path ? <a href={path}>{values.name}</a> : values.name}
    </li>
  );
})}

It is not working. Any idea how should I do it?

like image 242
myTest532 myTest532 Avatar asked Jun 07 '26 21:06

myTest532 myTest532


1 Answers

Issue

Strings can be spread since they are iterable, but null is not. Spreading a string doesn't make sense here though, you want to spread in a prop.

Solution

Create a prop object that can be spread into the element.

{props.path.map((values, index) => {
  const path = values.path ? `/${values.path}` : null;
  const aria = path !== null ? { "aria-current": "page" } : {};

  return (
    <li className="breadcrumb-item" {...aria}>
      {path ? <a href={path}>{values.name}</a> : values.name}
    </li>
  );
})}

Edit add-html-property-conditionally-in-react

Why key is "aria-current" and not ariaCurrent?

WAI-ARIA and Accessibility

Note that all aria-* HTML attributes are fully supported in JSX. Whereas most DOM properties and attributes in React are camelCased, these attributes should be hyphen-cased (also known as kebab-case, lisp-case, etc) as they are in plain HTML:

<input
  type="text"
  aria-label={labelText}
  aria-required="true"
  onChange={onchangeHandler}
  value={inputValue}
  name="name"
/>
like image 193
Drew Reese Avatar answered Jun 10 '26 11:06

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!