3

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?

1
  • Could you give me an example? Commented Dec 17, 2020 at 21:03

1 Answer 1

4

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"
/>
Sign up to request clarification or add additional context in comments.

4 Comments

Ah beat me to it, one question on this though - should it be ariaCurrent in camel case as React likes it?
@Ayushya No, aria attributes are still standard for accessibility: reactjs.org/docs/accessibility.html#wai-aria
@Ayushya No worries. :) I added a bit more explanation to my answer. Cheers.
@DrewReese if you're using TypeScript it's handy to know that you have to put {/* @ts-expect-error valid aria attribute */} before the element on which you're spreading the aria attribute (at least this was the case in my Next.js app on the Link component)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.