Use Images in CSS Files with Reactjs

Use images in CSS files with ReactJS

You can use (./) . Webpack automatically link the image
for eg:-

.user-background{
background: url("./images/all-bg-title.jpg") no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-ms-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

Above image(all-bg-title.jpg) is at folder /src/images/all-bg-title.jpg

React Docs Link here

How do I display an image with CSS in ReactJS?

Can you change the tag image to img

    <image src={burgerLogo} alt="MyBurger"/>

to

    <img src={burgerLogo} alt="MyBurger"/>

if the import import burgerLogo from '../../assets/images/burger-logo.png' is not correct, you will get an error, so that should not be a problem in your case.

Just want to point that user defined components should start with a capital letter.

When an element type starts with a lowercase letter, it refers to a
built-in component like or and results in a string 'div'
or 'span' passed to React.createElement. Types that start with a
capital letter like compile to React.createElement(Foo) and
correspond to a component defined or imported in your JavaScript file.

We recommend naming components with a capital letter. If you do have a
component that starts with a lowercase letter, assign it to a
capitalized variable before using it in JSX.

from the ReactJS docs

Coming back to your question

How do I display an image with CSS in ReactJS?

You can do that using CSS background-image property.

Put your image burger-logo.png in public folder (you can change location if needed eg: inside img or assets folder).

In you CSS use like this

.Logo {
background-color: white;
background-image: url('./burger-logo.png');
padding: 8px;
height: 100%;
box-sizing: border-box;
border-radius: 5px;
}


Related Topics



Leave a reply



Submit