Background image css react

How to set a background Image With React Inline Styles?

In ReactJS, we can use the ‘backgroundImage’ property of CSS to set the background image for a component or particular HTML element like div. Here, we will learn to set the background image using the inline styles.

Also, we will use the absolute and relative URLs to set the background image.

Syntax

Users can follow the syntax below to use the React inline styles to set the background image.

 Style =  backgroundImage: 'url("image-url")', >> > Div content 

In the above syntax, we have used the ‘backgroundImage’ CSS property to set the background image for the div element.

Example

We have created the div element in the example below and applied inline CSS. We have set the background image using the URL. Also, we have set the height and width of the div element using the CSS. Furthermore, we have set some CSS properties for the background image.

import React from "react"; export default function App() < return ( 

Using the React inline styles to set a background image

> > This div contains a background image.
); >

Output

Example

In the example below, we have created the imageStyle object outside the return statement of the functional component. We have added the background image in the imageStyle object.

After that, we used the imageStyle object as an inline style of the div. In the output, users can observe the background image for the div element.

import React from "react"; export default function App() < let imageStyle = < height: "350px", width: "600px", backgroundImage: 'url("https://img.freepik.com/free-photo/wide-angle-shot-singletree-growing-clouded-sky-during-sunset-surrounded-by-grass_181624-22807.jpg")', backgroundSize: "contain", backgroundRepeat: "no-repeat", color: "white", >; return ( 

Using React inline styles to set a background image

> This div contains a background image.
); >

Output

Example

In the example below, we have used the relative URL to set the background image. Users can add the images in the ‘public’ directory of the React application. After that, we can use the relative path like ‘/image_name’, or if we add the image to any folder inside the public directory, we need to use a relative path like ‘/folder_path/image_name’.

Here, we show the react application’s logo as a background image using the relative path.

import React from "react"; export default function App() < return ( 

Using relative URLs with React inline styles to set background image

> > This div contains a background image.
); >

Output

In this tutorial, we learn to set the background image using the React inline styles. We have used the absolute and relative URLs to set the background image using the ‘backgroundImage’ CSS property.

Also, users can use CSS properties to customize the background image, such as fixing the background image in the div and avoiding repetitions.

Источник

How To Use Background Images in React (With Example Code)

While basic text, shapes, and colors are great, we often need more in our web apps. Images are much more complex arrangements of text, shapes, and color, and can add a lot to your React app. In this article, we’ll learn how to use them. To use images in React, we use the style attribute backgroundImage. When added to a React component, backgroundImage displays an image to fill a specified portion of the element (or the whole element). Since React components are modular and easily configurable, background images in React are as well. To set backgroundImage, we use URLs to determine the image. These URLs can take several forms, and we will discuss them in this article. We’ll also learn how to do several operations to manipulate background image placement and display.

React Background Image Example

We’ll start with a simple example of a background image within a React element. We want to display the following image of the Upmostly logo: Within a React component. The image is located in the directory as follows: Let’s try displaying the image using the simplest way possible:

import image from "./img/UpmostlyLogo.png"; function Component() return ( div style= backgroundImage:`url($image>)` >>> Hello World div> ); > export Component >;

This component renders the following output: In this example, we first ‘import image’ from the path of the image we want to use. This allows the file to reference the image. To add the image to the component, we use backgroundImage. We set backgroundImage to the image we specified above. Notice that we convert the image to a URL with url(). url() is used to include a file within a CSS style (complete reference here). url() needs to be one string, so we concatenate it to the image variable. However, as we can see, the output may not be what we wanted. Many Upmostly logos get rendered, and they are all cut off so that we can only see the top of them. By default, background images in React are set to completely fill the bounds of the component, maintaining their original size. Since they are maintaining their original size, images duplicate and crop themselves in order to fully fill the component’s space. We need to modify the background image’s settings so that it displays what we want it to.

Manipulating backgroundImage

Fundamentally, React’s backgroundImage is the same as CSS’s ‘background-image’. All CSS ‘background-image’ manipulations will work with React (a complete reference can be found here). Let’s first remove all extra copies of the image; we only want one Upmostly logo to show on the screen. To do this, we set the backgroundRepeat property:

import image from "./img/UpmostlyLogo.png"; function Component() return ( div style= backgroundImage:`url($image>)`,backgroundRepeat:"no-repeat" >>> Hello World div> ); > export Component >;

The only thing we’ve changed is we’ve set backgroundRepeat to ‘no-repeat’. The following gets rendered: Now we only have one background image. However, it’s still cut off so that only the top is visible. This is because the image’s height is greater than the height of the component. Only the piece of the image that overlaps with the component is rendered. To solve this problem, we will fit the image to the React component:

import image from "./img/UpmostlyLogo.png"; function Component() return ( div style= backgroundImage:`url($image>)`,backgroundRepeat:"no-repeat",backgroundSize:"contain" >>> Hello World div> ); > export Component >;

All we did was add “backgroundSize: ‘contain’ ” to the div’s styles. This code renders the below: That’s really small, so we’ll now increase the size of the React component. This is really easy and straightforward; all we have to do is add a few more styles:

import image from "./img/UpmostlyLogo.png"; function Component() return ( div style= backgroundImage:`url($image>)`,backgroundRepeat:"no-repeat",backgroundSize:"contain", height:600,width:600 >>> Hello World div> ); > export Component >;

In the div’s styles, we set height and width to ‘600px’ each. The code renders the following: From here, we can make the background image as big or small as we’d like.

Getting Background Images from Other Sources

We now know how to use React’s backgroundImage with images within the ‘src/’ directory, but what if we want to use images outside the ‘src/’ directory, or from the cloud? ‘Create-react-app‘ generates another folder alongside ‘src/’, ‘public/’. We can store images here and render them through backgroundImage. When using an image from the ‘public/’ directory, we don’t have to do the import step we did in the first example. Instead, we can reference the image directly. With the following directory setup: We can reference the image directly:

function Component() return ( div style=backgroundImage:"url(/UpmostlyLogo.png)">>> Hello World div> ); > export Component >;

The only thing we’ve changed from the last example is the referencing of “UpmostlyLogo.png”. This time, we set backgroundImage to ‘url(/UpmostlyLogo.png)’, referencing the image from the ‘public/’ directory as if it was in the same folder as our React component. We get the same output: We can also pull images for backgroundImage from the cloud. All we need is an image URL that we can access. AWS S3 is a file storage service that can store images and generate usable URLs for them. While using S3 and the necessary callbacks is beyond the scope of this article, we will use an image URL for the following example. The following example is taken from a functioning web app. We pull the necessary URLs from S3, and use them to set the background images of our components. We’ll also log the URLs of the images we pull to the console:

console.log("URL set:", pulled_image_url)
render() return( // Handle data transfer through drag and drop. div> div> this.name> div> div> ) >

The above code generates the following output: We can see the image URLs in the console: As we can see in the URLs displayed above, we successfully displayed an image from the cloud. That’s it for backgroundImage in React. If you have any questions or comments, please don’t hesitate to leave them below!

👋 Hey, I’m Jesse Ryan Shue

I am a Full-Stack Developer and an Industrial/Mechanical Designer. I have work experience in Industrial Design, 3D printing, and teaching. I am experienced in Python, JavaScript, and SolidWorks CAD. Follow me on LinkedIn

Источник

React Background Image Tutorial – How to Set backgroundImage with Inline CSS Style

Nathan Sebhastian

Nathan Sebhastian

React Background Image Tutorial – How to Set backgroundImage with Inline CSS Style

There are four ways to set a backgroundImage style property using React’s inline CSS.

This tutorial will show you all four methods, with code samples for each.

Here’s an Interactive Scrim of Setting a Background Image with React

How to Set a Background Image in React Using an External URL

If your image is located somewhere online, you can set the background image of your element by placing the URL like this:

React-failed-to-compile-image

This way, you won’t show any broken image links on your web app. In the code above, the value of backgroundImage is set using a template string, which allows you to embed JavaScript expressions.

How to Set a Background Image in React Using the Relative URL Method

The public/ folder in Create React App can be used to add static assets into your React application. Any files you put inside the folder will be accessible online.

If you put an image.png file inside the public/ folder, you can access it at /image.png . When running React in your local computer, the image should be at http://localhost:3000/image.png .

You can then assign the URL relative to your host address to set the background image. Here’s an example:

Screen-Shot-2020-12-14-at-20.18.30

Don’t forget to adjust the backgroundImage value to url(/img/image.png) if you decide to create the folder.

How to Set a Background Image in React Using the Absolute URL Method

You can also include the absolute URL by using Create React App’s PUBLIC_URL environment variable like this:

absolute-url-background-image-1

The absolute URL will only be seen when you deploy React into production application later.

How to Set a Background Image with Additional Properties

If you want to customize the background image further, you can do so by adding additional properties after the backgroundImage . Here’s an example:

 
)`, backgroundRepeat: 'no-repeat', width:'250px' >>> Hello World

The properties set above will add background-repeat: no-repeat and width: 250px together with the background-image style to the element.

Thank you for reading, and I hope you found this article useful. If you have any questions, you can find me on Twitter. I will share some short developer tips from time to time as well. 🙂

Nathan Sebhastian

Nathan Sebhastian

JavaScript Full Stack Developer currently working with fullstack JS using React and Express. Nathan loves to write about his experience in programming to help other people.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Читайте также:  Create bin file python
Оцените статью