Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react';
import Slick from 'react-slick';
import style from './Slider.module.css';
import {Link} from 'react-router-dom';

const SliderTemplates = (props) => {

    let template = null;
    const settings= {
        dots:true,
        infinite: true,
        arrows: false,
        speed: 500,
        slidesToShow:1,
        slidesToScroll:1
    }

    switch(props.type){
        case('featured'):
            template= props.data.map((item, i)=>{
                return(
                    <div key={i}>
                        <div className={style.featured_item}>
                            <div 
                                className={style.featured_image} 
                                style={{ background: `url(../../Assets/images/articles/${item.image})` }}>
                                <Link to={`/articles/${item.id}`}>
                                    <div className={style.featured_caption}>
                                    {item.title}s
                                    </div>
                                </Link>
                            </div>
                        </div>
                    </div>
                )
            })
            break;
        default: 
            template=null;
    }
    return (
        <Slick {...settings}> 
            {template}
        </Slick>
    );
};

export default SliderTemplates;
.featured_item{
    position: relative;
}
.feature_item a{
    position: absolute;
    width: 100%;
    bottom: 0px;
    text-decoration: none;
    right: 0px;
}
.featured_image {
    height: 330px;
    background-size: cover !important;
    background-repeat: no-repeat !important;
}
.featured_caption{
    color: #fff;
    top: 0px;
    width: 100%;
    padding: 20px;
    font-weight: 300;
    font-size: 28px;
    box-sizing: border-box;
}

I am attempting to display images with inline styling in ReactJS fetched from a folder (Location provided in the attached image). The information is sourced from db.json but I am facing difficulty in rendering the images properly. Despite setting the positions for image and text correctly, the picture does not appear on the screen. Any assistance in resolving this issue would be greatly appreciated.Screenshot

Answer №1

Give this a try:

Instead of using

url(../../Assets/images/articles/${item.image})
in your background image style, you can consider placing your images in the public folder for better performance. Here's how you can implement it:

style={{ backgroundImage:url(${process.env.PUBLIC_URL}/images/articles/${item.image})`

To learn more about handling static assets in React, check out the following link: https://create-react-app.dev/docs/using-the-public-folder/

Answer №2

To specify a background image using CSS, you should use the property backgroundImage. Also, make sure to import the images from the designated folder by following this procedure:

style={{ backgroundImage: `url(${require('../../Assets/pics/articles/'+item.image+''})` }}

Answer №3

To include the image in a folder within React, simply designate it as a background image using standard CSS techniques.

.featured_image {
    height: 330px;
    background: url('./(IMAGE PATH HERE)') no-repeat center center / cover
}

Additionally, consider capitalizing your styles when using .module.css and avoid using hyphens or underscores. I suggest renaming to .FeaturedImage, then updating in your JSX - className={style.FeatureedImage}

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

The mic recording feature for converting to MP3 is malfunctioning on smartphones and tablets

My goal is to implement audio recording for both web and mobile applications. I have utilized the mic-recorder-to-mp3 library for this purpose, which functions well on desktop browsers but encounters issues on Android and iOS mobile browsers. Despite tryin ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Updating dropdown selection with ng-model in AngularJS

nameList includes [“Julia”, “Evan”, “Tomas”]; select ng-model=“names” ng-options=“x for x in nameList” In my controller, I make a service api call to GetNameByID/{id}” and based on the id, I need to set the default value of the drop ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

Choose CSS Option

I need assistance with customizing my dropdown select option - see the example below <select> <option value="volvo" title="NEED THIS BIGGER AND FORMATED" >Volvo</option> <option value="saab">Saab</option> <option val ...

Issue with displaying content within a custom element for children was not seen

The content within the 'Child content' span is appearing in the Light DOM, but for some reason it's not being displayed on the actual page (refer to the screenshot provided). Does anyone have any insights as to why it might not be visible? ...

The CSS media query isn't functioning properly on Safari browser

Currently, I am working on a project using React JS and CSS. In order to make it responsive, I have implemented media queries. However, I have encountered an issue where the media query is not functioning properly in Safari browsers on both phones and PC ...

Tips for managing a date picker with JavaScript using the Selenium WebDriver

I have been attempting to scrape a travel website using Selenium Webdriver and Python. While I have successfully set the destination (destino) and place of origin (origem), I am encountering difficulties when trying to select a date. I understand that Ja ...

Express does not provide a 304 response code for static json files

I have a situation where I am utilizing express.static to serve a large static json file. It seems that express.static is always returning a 200 status code for the static json file, even when it remains unchanged. Given the file's size and the speci ...

Hiding content and troubleshooting video playback problems in FancyBox

I'm facing an interesting issue. I've implemented FancyBox lightbox to showcase a "video" tag when users click on the image thumbnail, and it functions well with all varieties of HTML5 video. The challenge arises when testing in browsers older th ...

Navigating in AngularJS with various URL parameters

Within my application, I am in need of using routes that require multiple attributes from the URL to be passed into PHP. The current setup that is functioning correctly is as follows: .when('/jobs/:type', { templateUrl: function(attrs){ ...

AngularJs promise is not resolved

Before processing any request, I always verify the user's authorization. Here is the factory code that handles this: (function() { angular.module('employeeApp').factory('authenticationFactory', authenticationFactory); fun ...

Unable to fetch the identification number from the database

I'm encountering an issue with retrieving the ID from my database: https://i.sstatic.net/oSAi8.jpg Here is a snapshot of my database: https://i.sstatic.net/j5PpZ.jpg Below is my event controller class: <?php namespace App\Http\Contro ...

Plugin refresh after callback

I have a webpage that features a row of buttons at the top, followed by some content below. Whenever one of the buttons is clicked, the content is updated using UpdatePanels. Within this content, I am attempting to incorporate the royal slider plugin, wh ...

Utilizing Vue CLI's sourcemaps to pinpoint the styling within a Vue component file

Currently, I am working on a Vue CLI project. After setting up the project and making some development changes, my package.json file now includes: package.json "dependencies": { "bootstrap": "^4.3.1", "core-js": "^3.0.1", "preload-it": "^1.2. ...

The function in jQuery that can be used to hide a <div> when clicked

I am facing a problem with my jQuery code that is supposed to remove/hide a specific div. Despite checking various examples, I can't seem to make it work properly. This issue arises in the context of jQuery on Drupal 7. The live site where this proble ...

The problem with legends in chart.js not displaying properly

I've been struggling to display the labels "2017" and "2018" as legends on the right side of the chart. I've tried numerous approaches but haven't found a solution yet. The purpose of showing these legends is to easily identify that each co ...

Is there a way to convert inline styling to CSS using Material-ui within a React component?

In my development work with React, I initially utilized inline styling to customize the appearance of material-UI components. However, I have come to realize that utilizing CSS provides a more structured and efficient approach to styling components. Despit ...