A complete beginner's guide for adding and styling images in React js.
- Adding the image (the different ways)
- Styling the image
- Example Code
There are several different ways of inserting images in React.
- Using the image tag
Using the <img/> tag you will need to provide it with two values:
“src” (source): the URL or the path of the image.
“alt” (alternate): an alternate text in case of the image not being available.
<img src="https://reactjs.org/logo-og.png" alt="React Image" />
- Setting a background image
Using CSS you can set the background of any element. This is most use when you want to display content over the image.
.app {
background-image: url(https://reactjs.org/logo-og.png);
}
With the <img/> tag
Drag your image into your project and import it into the desired component. Afterward, you can insert the name of the import into the source property.
Inserting a local background image
Just like before you would import the image. Then you would insert it using CSS URL(…) or using inline styling as shown below.
Structuring your code
The correct way to structure images in your project is to add them in an “images” folder. If you are using other assets than just images, you might want to add all the assets folders into one, as shown below.
Drag in the left sidebar to see the source code
The most useful styling properties for images include:
- Width and/or height: Setting the width and heights of the element
- Border-radius: Curving the edges of the element
- Filter: Learn more about filters…
- Opacity: Decimal value desciping the opacity of the element
<img/> specific:
- Vertical-align: Snapping the image verticly
background image specific:
- Background-image: Path or image URL
- Background-repeat: Setting image repetition for each or both axis
- Background-size: Setting the size of the image
- Background-position: Setting the position of the image in the background
This is my first post, so please leave a comment on what you thought about it so that i can improve and provide the best possible content!