I have done to set the code like this, but whenever i execute the code i recieve an error, how can i fix the error
import React from 'react';
const ImageList = props => {
const image = props.images.map((image) => {
return (
<div>
<img src={image.urls.regular} />
</div>
)
});
return <div>{image}</div>
};
export default ImageList;
The error i receive in the following :
Line 5: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images jsx-a11y/alt-text
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
Compiling...
Compiled with warnings.
As ChrisR and tenor528 mentioned, it's self-explanatory. You need to add an alt attribute to your images. Ideally, your image tag should be like this:
<img src="linkToImage" alt="description of Image">
alt attribute useful for accessibility purposes. For example, when someone is using a screenreader, the alt text would be read. That's why ESLint is giving you a warning.
Also, it is mentioned in the error, how to solve it:
1- Either add a description.
2- Put empty string.
So, in your case, if you are not getting the description in the props, replace
<img src={image.urls.regular} />
with
<img src={image.urls.regular} alt="" />
While if you are getting the description, to simply put that in your alt tag like alt={image.description}.
Related
I am creating a gatsby website that uses the flickity-react-component to display a slider with product images. I believe that I should use the gatsby image to make it load faster, but when I try it, the Image does not display (it is 0x0 pixels).
This is the code I am trying to run:
const ThirdPage = ({ data }) => {
...
function Carousel() {
return (
<Flickity
className={'carousel'} // default ''
elementType={'div'} // default 'div'
options={flickityOptions} // takes flickity options {}
disableImagesLoaded={false} // default false
reloadOnUpdate // default false
static // default false
>
<Img fluid={data.imgPrincipal.childImageSharp.fluid} alt="Mulher a lavar o cabelo com o chuveiro ecológico" />
<img src="https://placeimg.com/640/480/nature" />
<img src="https://placeimg.com/640/480/nature" />
<img src="https://placeimg.com/640/480/architecture" />
</Flickity>
);
}
The "Img" is the one using the gatsby image, the others are what I had before.
This is the result
I don't get an error when running this, I believe this might be because gatsby-image creates a div.
Can someone help me make this work? I am a beginner, so if it's something very advanced, I would appreciate an alternative ... Thank you.
Indeed, gatsby-image is not only a simple image. It creates a wrapper with a few nested div HTML structure inside to make the blur effect and the rest of the improvements.
Take a look at gatsby-image docs:
Note: gatsby-image is not a drop-in replacement for <img />. It’s
optimized for fixed width/height images and images that stretch the
full-width of a container. Some ways you can use <img /> won’t work
with gatsby-image.
It may not work with all sliders.
I've used it with other sliders that accept a nested structure inside, not only a single <img> tag such as Swiper or Slick.
I am doing a code challenge and am very new to React. I am used to hard coding things, and I need to loop in data from a JS file. I am familiar with HTML and CSS so styling will be no problem, but how I can pull in the data from the menu items without hardcoding. Below are links to what I have in the project files as well as a reference as to what it should look like. Thanks!
[1]: https://i.stack.imgur.com/JtE4X.png
[2]: https://i.stack.imgur.com/n412K.png
[3]: https://i.stack.imgur.com/ZVSl2.png
Here's a simplified example
Interactive sandbox
https://codesandbox.io/s/lucid-lovelace-kr6rr?fontsize=14&hidenavigation=1&theme=dark
Here's the code:
function myComponent() {
// Here's your data
// You'll probably want to set this to state after fetching it
// (It doesn't need to be in a const)
const myList = [
"https://i.stack.imgur.com/JtE4X.png",
"https://i.stack.imgur.com/n412K.png",
"https://i.stack.imgur.com/ZVSl2.png"
];
// map over your data
// here we are rendering an html img for each item
// and we give each a key to help react keep a record of what is has rendered
return (
<div>
{myList.map(url => <img src={url} key={url} />)}
</div>
)
}
Hope it helps!
On line 19, try
let menuItems = this.state.menuItems.map((item) => {
<MenuItem name={item.name} img={item.imageName} price={item.details.price} />
}
Then in your return,
<div id="combo-header">
<h1>Combo Meals</h1>
{menuItems}
</div>
You can also choose to loop within your render instead of assigning to its own menuItem variable.
<div id="combo-header">
<h1>Combo Meals</h1>
{this.state.menuItems.map((item) => {
<MenuItem name={item.name} img={item.imageName} price={item.details.price} />
}}
</div>
Note that the second option requires the javascript to be wrapped in {} so that you can write javascript directly in the JSX.
After this, you'd write a MenuItem component that would intake the props above.
You will also have to perform a check that the array is not empty before mapping over it, or there will be errors.
What I am trying to achieve is that a particular image should be loaded for a div, when present. A default image should be loaded for all other divs for whom specific (depending on the name) image is not present.
const defaultImg = require('../images/default.jpg');
But this is the value that console returns for defaultImg - "image /static/media/default.47ce6e77.jpg"
<img src={require(`../images/${imageUrl}.jpg`)} //if I remove ther require form here then the default image is loaded for eveerything, even when the particular image is present.
onError={(event) => event.target.setAttribute("src", {defaultImg})} alt="" />
Instead of the defulat image getting loaded, it throws
Error: Cannot find module './<image-name>.jpg'
I also tried using React Image Fallback
{/* <ReactImageFallback
src={require(`../images/${imageUrl}.jpg`)}
fallbackImage={defaultImg}
initialImage="loader.gif"
alt="A cool image should be here"
className="project-pic"
/> */}
Doesn't work any different.
If const defaultImg = require('../images/default.jpg');
Why does it become /static/media/default.47ce6e77.jpg ?
Check your source in devtool. Your img might be showing as <img src="[object Object]" alt="">.
Replace your onError with onError={(event) => event.target.setAttribute("src", defaultImg)}. You are passing defaultImg as object.
Considerusing the fallback image:
<img src={imagesrc}
onError={(e) => {
e.target.onerror = null
e.target.src = fallbackImg}
} />
I have a file which contains an array of objects which have the values:
{
id: ..,
image: "require('./React.png')",
name: ...,
description:...,
technology:..,
},
The image value contains the file path of the image file I would like to use as a string. The image is in the same directory as my component and object file.
When I destructure the props I am able to pass the id, name, description, and technology values to my component and they are displayed on the app fine. When I place the image prop inside of the image source attribute within the image tag the image is not displayed. (I am using JSX)
I've tried passing the image prop like: {this.props.image}/{props.image} to no avail.
The last P tag contains the same image prop I am trying to pass to my image source and it displays the route to my file as a string: "require('./React.png')". So I know the prop is accessing the object value correctly. The image source attribute is just having a fit for some reason. Any help would be appreciated. Thanks.
const ProjectCard =({image, name, description, technolgy})=>{
return(
<div className='pa3 dib br2 ma2 bw2 shadow-5 grow tc'>
<img src={{image}} style={{width:"60px", height:"60px"}} alt='logo'/>
<div>
<h2>{name}</h2>
<p>{description}</p>
<p>{technolgy}</p>
<p>{image}</p>
</div>
</div>
Well, you literally wrote a string with the content "require('./React.png')", which means that will get passed down to your <img> component as src property. Since the string is not a valid URL, nothing will be displayed. Maybe your browser will display an error.
You have two options. Either you modify the string to be a correct URL by removing the require from the string; for example, you change it to "./React.png". But then you need to configure your backend to actually serve this image for you.
Option two is to import that image in your javascript code into a variable and pass that to the src property of your <img> tag.
For example like this:
import reactImage from './React.png';
const ProjectCard =({name, description, technolgy})=> (
<div className='pa3 dib br2 ma2 bw2 shadow-5 grow tc'>
<img src={{reactImage}} style={{width:"60px", height:"60px"}} alt='logo'/>
<div>
<h2>{name}</h2>
<p>{description}</p>
<p>{technolgy}</p>
<p>{image}</p>
</div>
</div>
);
But here is the catch. Since it looks like you are trying to display images dynamically, I would suggest you go with option 1 and NOT make images part of your bundle beforehand. Only do that with images that are a fixed part of your application, like icons or a logo.
Dynamic (content) images should be served from a web server.
Change value if the image in JSON to this:
{
...
image: require('./React.png'),
...
}
<img style={{ width: 300 }} src={ props.image } />
I'm trying to render some html, stored in a DB, and put a component inside.
It'd look like this:
import ReactMarkdown from 'react-markdown/with-html';
const inlineCode = (props) => <Gist id={props.value} />;
const source = '`7df0c9a5d794504a28bd3256b7bf5c4f` <p>asdasdasd</p><h1>title</h1>';
ReactMarkdown is used like this:
<ReactMarkdown source={source} renderers={{ inlineCode }} escapeHtml={false} />
The result is is rendered properly and the block is also, but isn't, the contents are outside of the block.
If I wrap the whole source with a <div>, the <Gist/> is rendered as text and <p>/<h1> are rendered properly.
What am I missing? I'm trying to store html with custom components inside, <Gist/> is just an example. Suggestions for a (more) suitable library are also welcome. Example ideal source I'd like to store in a db and then render in a React component:
<div>
<p>
<CustomReactComponent/>
<br/>
test
</p>
<Gist/>
</div>
Okay I found this lib: https://github.com/probablyup/markdown-to-jsx
If your source looks like:
const source = `<gist id="yourIdHere" /> <h1>asdasdasd</h1>`;
<Markdown
options={{
overrides: {
gist: {
component: renderGist,
},
},
}}
>
{content}
</Markdown>
It renders both the <Gist> and the normal <h1> as <h1. Paragraph tags seem to be automatically added if you add line breaks and something like # Title is also automatically wrapped.
<Gist> in source is converted to lowercase, so it'd only matter for the overrides object (lowercase again). Handles all my custom stuff and html predictably.