1

How can I add variable bgImg to background-image URL?

let bgImg = props=>props.bgImg;

//this will show error
export const Users = styled.div`
    background-image: url(${require('../../assets/images/' + {bgImg} + '.svg')});
    background-image: url(${require('../../assets/images/' + ${bgImg} + '.svg')});
`;

I have tried this and it didn't work

let x = '../../assets/images/';
let bgImg = props=>props.bgImg;
let result = x + bgImg + ".svg";

Result with error

../../assets/images/function bgImg(props) {
    return props.bgImg;
}.svg

How can I get that return property?

4
  • 1
    You're defining bgImg as a function. What is it you expect to pass into that function? Nothing in what you've shown actually calls it. Commented Sep 12, 2018 at 14:24
  • props is already in scope, why not just do let bgImg = props.bgImg? Commented Sep 12, 2018 at 14:24
  • Create the string before you pass them to require, it should be easier one. Commented Sep 12, 2018 at 14:30
  • You can avoid all the problem by using the svg inline as a react element and rendering the <svg>...</svg> directly into the DOM. Commented Sep 12, 2018 at 14:41

1 Answer 1

1

The feature are you looking for maybe dynamic import

import("./math").then(math => {
  console.log(math.add(16, 26));
});

But specifically what you'll find very useful is Loadable implementation:

import Loadable from 'react-loadable';

const LoadableOtherComponent = Loadable({
  loader: () => import('./OtherComponent'),
  loading: () => <div>Loading...</div>,
});

const MyComponent = () => (
  <LoadableOtherComponent/>
);

And maybe that's what you're looking for:

Loadable.Map({
  loader: {
    Bar: () => import('./Bar'),
    i18n: () => fetch('./i18n/bar.json').then(res => res.json()),
  },
  render(loaded, props) {
    let Bar = loaded.Bar.default;
    let i18n = loaded.i18n;
    return <Bar {...props} i18n={i18n}/>;
  },
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.