Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify an empty alt attribute in React/JSX?

I'm trying to add an empty alt attribute to an img element in a react component like so

function SomeImageComponent(props) { 
  return <img src={props.imgSrc} alt="" />;
}

But when this is rendered to the DOM and I inspect it in dev tools I see a boolean type of attribute like this

<img src="/path/to/cat.gif" alt />

When I then test this with VoiceOver it ignores the valueless alt attribute and reads out the path to the image. So how can I get react to render an empty string for the attribute value?

like image 461
warmanp Avatar asked Jun 19 '17 13:06

warmanp


2 Answers

alt and alt="" are the same thing. From the spec:

Attributes can be specified in four different ways:

Empty attribute syntax

Just the attribute name. The value is implicitly the empty string.

...

It's true that you typically see this with boolean attributes, but it's not limited to them.

Example:

var imgs = document.querySelectorAll("img");
var alt0 = imgs[0].getAttribute("alt");
var alt1 = imgs[1].getAttribute("alt");
console.log("0 (" + typeof alt0 + "): '" + alt0 + "'");
console.log("1 (" + typeof alt1 + "): '" + alt1 + "'");
<img src="foo.png" alt>
<img src="bar.png" alt="">

It's worth noting that there are only a very few places where a blank alt is appropriate, but if you're supplying it at all, you're probably someone who's already aware of those places. :-)

like image 155
T.J. Crowder Avatar answered Sep 22 '22 12:09

T.J. Crowder


Can we also add alt tags? By doing this, we can overcome Google & tools errors notifications

<img src="foo.png" alt="foo">
<img src="bar.png" alt="bar">
like image 33
anil Avatar answered Sep 23 '22 12:09

anil