Using Background Images in React Components

I am looking to achieve a similar effect of setting the image as a background-url with specific styling attributes. Here is the CSS code snippet:

img.thisIsMyImage {
 background: url("../../services/images/hehe.jpg") no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover; 

animation: increase 60s linear 10ms infinite;
-webkit-transition: all 5.2s ease-in-out;
-moz-transition: all 5.2s ease-in-out;
-ms-transition: all 5.2s ease-in-out;
-o-transition: all 5.2s ease-in-out;
transition: all 5.2s ease-in-out;

}

Now, I have integrated this React component:

 render() {
    return (
    <div>
        <img src={rsm_logo} className="thisIsMyImage" alt="containerLogo" />
        <LoginForm submit={this.submit} />
    </div>
    )
}

The above code works perfectly in CSS, but I aim to apply these styles to the element within the .jsx code under "thisIsMyImage" while maintaining the same behavior. Any suggestions or tips are highly appreciated. Thank you.

Answer №1

CustomBackground.js

import './MyStyle.css'
import MyImage from '../path/to/image.jpg'

export const CustomBackground = () => {
    return (
      <>
        <img className="customBackground" src={MyImage} alt={"Error"} />
      </>
    )
}

MyStyle.css

.customBackground {
    width: 100%;
    height: 100vh;
}

Answer №2

To include a CSS file in a React component, follow these steps:

 // Modify the class name in the CSS file
 thisIsMyImage {
     background: url("../../services/images/hehe.jpg") no-repeat center center fixed; 
  }

 // Apply the modified class in the CSS file:
 .thisIsMyImage {
   background: url("../../services/images/hehe.jpg") no-repeat center center fixed; 
 }

Import the CSS file in your React component:

import from './styles.css'

<img src={rsm_logo} className="thisIsMyImage" alt="containerLogo" />

Answer №3

Why are both src and background used in the img tag here? It seems unusual to combine them like this. The img src will take precedence over the background image. Make sure to specify appropriate width and height for the image to display correctly.

Here is an example using a div with the img tag:

.thisIsMyImage {
    background: url("https://via.placeholder.com/150") no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
    animation: increase 60s linear 10ms infinite;
    -webkit-transition: all 5.2s ease-in-out;
    -moz-transition: all 5.2s ease-in-out;
    -ms-transition: all 5.2s ease-in-out;
    -o-transition: all 5.2s ease-in-out;
    transition: all 5.2s ease-in-out;
    width:150px;
    height:150px;
}
<div class="thisIsMyImage" title="containerImage"></div>

<img src="https://via.placeholder.com/150" class="thisIsMyImage" title="containerImage" />

To prevent multiple imports, it is advised to import the CSS file into the main file:

import from './styles.css'

In the render function, consider using a div instead of an img tag when utilizing background and related properties:

render() {
  return (
    <div>
      <div className="thisIsMyImage" title="containerLogo" />
      <LoginForm submit={this.submit} />
    </div>
  )
}

Answer №4

You have the ability to bring in CSS and define the class

class Greetings extends React.Component {
  render() {
    return (
    <div>
      Greetings {this.props.name}
        
        <div className='pictureStyle' />
      </div>
);
  }
}

ReactDOM.render(
  <Greetings name="Universe" />,
  document.getElementById('container')
);
.pictureStyle {
  background: url("https://placekitten.com/600/200") no-repeat center center fixed; 
  
  width: 600px;
  height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to creating a continuous loop for CSS3 animation

I'm looking to create a setup that can play on repeat, but I'm not very familiar with jQuery. Can anyone lend a hand with this? Check out the DEMO here $('.title1').fadeIn('fast', function() { $('div').addClass ...

I encountered an error while trying to delete using Axios in React. Can someone please help me troub

Currently, I am utilizing the PHP API to retrieve data from MySQL and verifying it using Postman. Everything seems to be functioning well except for the delete operation when using React on the front end. Despite hardcoding the value, the error message p ...

Using React-Router-Config to dynamically set the page title

I am seeking advice on how to dynamically set page titles using the configuration file in conjunction with react-router-config. Should I use props or Helmet for this purpose? routes.js const routes = [ { title: 'Home', path: ...

What are the steps to implement a personalized material design theme on a Bootstrap component?

Utilizing Angular Material design components across my entire website for a cohesive look and feel. (Angular Material Design) A custom theme has been crafted: $mdThemingProvider.theme('default') .primaryPalette('red', { ...

Positioning Text in CSS/JS Navigation

Looking for assistance on aligning the text in the menu located at: 1st tab: I would like a line break after "Item". 2nd and 3rd tabs: I am seeking a line break after "This is". I have only included the section of the menu that requires adjustment, whi ...

Create a stylish block element with vertical gaps between each line, extending to full width except for the final line

Is there a way to create a title like this: https://i.sstatic.net/iSw34.png I've experimented with various options on https://jsfiddle.net/hx4m9kfa/, but using display: inline-block; is not working, nor is display: block or anything involving width: ...

Displaying images on the left side using CSS is causing issues in an ASP.NET project

Having trouble displaying a girl image in asp.net. I'm aiming for the following result: The problem is that the girl's face is not showing up correctly as shown below: This is the CSS I have created: .testimonialstilabel { background-image ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

A guide on transferring CSS module generated classes to components in Vue

Looking to implement CSS Modules, however, it appears that vue does not have a built-in method to pass generated class names to child components. Consider the scenario with two components: Table.vue TableRow.vue With styles like this: .table { table ...

Ensuring Visibility of Elements After Scrolling in react-native: A Guide to Tracking Impressions and Clicks

Is there a way to determine if an element is visible after scrolling in react-native? I've seen some examples for react, but I need something specifically tailored for react-native. My goal is to monitor impressions and clicks. ...

Issues with WordPress's multiple menu functionality not functioning as expected

I've been working on setting up multiple menus in WordPress, and I've run into a little issue. I managed to create the menus, assign them to their respective locations, and save them successfully. However, when I try to call the footer menu, it e ...

The deployment of a React application to AWS Amplify encounters an error in the Amplify Console

When I try to deploy my application using the AWS Amplify console, the Build step for the backend fails. The error message indicates that there is a missing configuration file or directory. { Error: ENOENT: no such file or directory, scandir '/code ...

Why does my value always revert to 0 whenever I switch screens while utilizing async storage?

Utilizing a stack Navigator, my primary screen is tracker.js, and the secondary one is macros.js. In macros.js, I have the ability to manually input nutritional macros (calories, Fats, Carbs, Protein) and add them to my UsedDailyCalories. However, when I ...

Is there a way to perfectly align the content at the center of the section?

I'm trying to ensure that the content in each section is centered. What is the correct way to achieve this? Should I focus on the containers/rows for alignment? I have tried placing the alignment properties in different elements (section, container, r ...

Having trouble executing a node module on a Windows system?

I am encountering an issue while trying to run npm run start-dev. I have been unable to resolve it on my own and could use some assistance. Here is a screenshot of the problem: https://i.stack.imgur.com/Qx243.png ...

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

To access the dropdown submenu on the Bootstrap nav bar via mobile, a prolonged tap is required rather than a single tap for it to work properly

Hey there, need your help with something interesting! If you head over to and look at the third link in the nav bar, you'll see a dropdown with a submenu. Everything works smoothly on a PC - just hover your mouse and it opens up. But when you try it ...

Examining a Next.js component using testing-library that is dependent on tRCP

After exploring tRCP, I decided to implement it in my Next.js project by following the setup instructions provided in the official documentation here: However, I encountered a challenge when trying to test a simple component that relies on tRPC, like this ...

Storing information while navigating with react routers

I am working on a project where I need to create multiple pages with forms. As the user navigates from one page to another, I want the data they entered to be saved automatically in the state of that component. The user has not submitted anything yet and t ...

Create two floating divs that adjust their height dynamically to be equal

Situation: I have a container with two direct children, known as "left" and "right". The height of the "left" child should never exceed the height of the "right" child. However, the "right" child can extend beyond the height of the "left" child. I am stru ...