Home > Software engineering >  Unable to get image using background property in React
Unable to get image using background property in React

Time:11-06

I am trying to make cards from an array of objects containing ids and URL (relative paths ) to my images. But when I try to use mapping to return arrays and use background CSS property to set images I am unable to do it. Below is the code

import React from "react";
import { useState } from "react";
import { Fragment } from "react";
// import { Link } from "react-router-dom";
import styles from "../Styles/Services.module.scss";
const Services = () => {
  const [pic, setPic] = useState(1);

  const list = [
    { id: 1, url: "../Images/mentorship.jpg" },
    { id: 2, url: "../Images/entertainment.jpg" },
    { id: 3, url: "../Images/support.jpg" },
    { id: 4, url: "../Images/opportunity.jpg" },
    { id: 5, url: "../Images/counselling.jpg" },
  ];

  // const clickHandler = (e) => {
  //   console.log(e.target.value);
  //   setPic(e.target.value);
  // };

  return (
    <Fragment>
      <section
        className="bg-light p-5 text-dark"
        style={{ fontFamily: "Lato" }}
      >
        <div className="container py-5 ">
          <div className="display-2 text-center">Our Services</div>

          <div className={`${styles.bodyCard}`}>
            <div className={`${styles.options}`}>
              {list.map((x) => {
                var a = x.url;
                return (
                  <div
                    key={x.id}
                    value={x.id}
                    className={`${styles.option} ${
                      pic === x.id ? styles.active : ""
                    }`}
                    onClick={() => setPic(x.id)}
                    style={{
                      background: `url(${
                        require(a).default
                      })`,
                      backgroundSize: "auto 100%",
                      backgroundPosition: "center",
                    }}
                  >
                    <div className={`${styles.shadow}`}></div>
                    <div className={`${styles.label}`}>
                      <div className={`${styles.icon}`}>
                        <i className="fas fa-walking"></i>
                      </div>
                      <div className={`${styles.info}`}>
                        <div className={`${styles.main}`}>Blonkisoaz</div>
                        <div className={`${styles.sub}`}>
                          Omuke trughte a otufta
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
              ;
            </div>
          </div>
        </div>
      </section>
    </Fragment>
  );
};

export default Services;

I am unable to display images at code background

background: `url(${require(x.url).default})

But When I use this it works.

background: `url(${require("../Images/mentorship.jpg").default})

It gives this error in React enter image description here

**Kindly do not make it a duplicate as I have checked other similar questions as well and have found no answer there. Thanks **

CodePudding user response:

    import React from "react";
import { useState } from "react";
import { Fragment } from "react";
// import { Link } from "react-router-dom";
import styles from "../Styles/Services.module.scss";
import image1 from "../Images/mentorship.jpg";
import image2 from "../Images/entertainment.jpg";
const Services = () => {
    const [pic, setPic] = useState(1);

    const list = [
        { id: 1, url: image1 },
        { id: 2, url: image2 },
    ];

    // const clickHandler = (e) => {
    //   console.log(e.target.value);
    //   setPic(e.target.value);
    // };

    return (
        <Fragment>
            <section
                className="bg-light p-5 text-dark"
                style={{ fontFamily: "Lato" }}
            >
                <div className="container py-5 ">
                    <div className="display-2 text-center">Our Services</div>

                    <div className={`${styles.bodyCard}`}>
                        <div className={`${styles.options}`}>
                            {list.map((x) => {
                                var a = x.url;
                                return (
                                    <div
                                        key={x.id}
                                        value={x.id}
                                        className={`${styles.option} ${
                                            pic === x.id ? styles.active : ""
                                        }`}
                                        onClick={() => setPic(x.id)}
                                        style={{
                                            background: `url(${a})`,
                                            backgroundSize: "auto 100%",
                                            backgroundPosition: "center",
                                        }}
                                    >
                                        <div className={`${styles.shadow}`}></div>
                                        <div className={`${styles.label}`}>
                                            <div className={`${styles.icon}`}>
                                                <i className="fas fa-walking"></i>
                                            </div>
                                            <div className={`${styles.info}`}>
                                                <div className={`${styles.main}`}>Blonkisoaz</div>
                                                <div className={`${styles.sub}`}>
                                                    Omuke trughte a otufta
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                            ;
                        </div>
                    </div>
                </div>
            </section>
        </Fragment>
    );
};

export default Services;

CodePudding user response:

I don't see why you need require. Try replacing:

background: `url(${require(x.url).default})

with

background: `url({x.url}`)

CodePudding user response:

As mentioned in the answerer above by https://stackoverflow.com/users/12902108/samira , it will work, just set style as style={{ background: `url(${photo})` }} assuming image is imported as photo .

  • Related