Background-Image in React Component

background image not showing in React

You shouldn't keep your images in the public folder. When using css inside the src folder you should use the relative path to the image file and during build react manages and updates the paths to their public build one.

src: https://github.com/facebook/create-react-app/issues/1248#issuecomment-266313612

If you want to keep your image inside public, you can try using '../../../../Public/images/img-2.jpg' as the path, altough it is recommended to keep your images inside src and let react manage them during compile.

React component as backgroundImage

backgroundImage is a CSS property that needs a URL path to the image, you can download the icon and add it locally to your project.

Or you could achieve the same result by using the CSS property z-index

Using styled-components we can style the component by adding it behind the main content by using the CSS Property z-index.

 const Icon = styled.section`
..
z-index: -1;
`;

We then add it around the Icon to style it as we want.

          <Icon>
<FaCar />
</Icon>

Link to sandbox:
https://codesandbox.io/s/wild-grass-sk9d9?file=/src/App.js

How i can apply a background image to the body of only ONE Component React

You have to wrap each component in a different div.

<div>
Navbar
</div>

<div style={{backgroundColor: 'color here'}}>
Contact us
</div>

Style inside the div or add a className and style in a separate file with CSS:

<div className="yourClass">
Contact us
</>

and in a separate .css file:

.yourClass {
background-color: 'color name';
}

react inline style backgroundImage not shown

You need to import the image.

import imageFilename from '../../../assets/img/picture.jpg';


Related Topics



Leave a reply



Submit