2018-05-09-importing-images

I always seem to have this recurring problem getting images into react components whose sole purpose is to handle images.

Problem

You can import an image from a local source easy enough, but I want to pass a reference to the image in as a prop, and props aren’t available outside the class.

I can require() an image url within class easily enough, but this function only seems to accept literal URLs, not props.sourcePath (or whatever I’ve called it).

And then I get confused passing this stuff through to styled-components. It feels marginally less complicated to use an <img /> tag since the src can sit right on there and can be accessed more easily by whatever approach I’m taking. When I want to use an image as background-image on a styled.div… man, I’m lost.

You can find stuff about this online, but it’s not as straightforward to find and adapt a solution to this as it seems to be with most things I get stuck on.

(current) Solution

After my latest round of trial and error, I’ve landed up with a pattern that seems to work and doesn’t rely on changing my webpack configuration or anything, which I’m sure is worth figuring out, but maybe not right now.

  1. create an object that requires the local url:
const icons = {
  secretMessage: require('./assets/secretMessage.png'),
}

export default icons;
  1. import the object to any component that needs an image:
import icons from './icons';
  1. pass a name reference as a props:
        <ProjectIcon 
          name="secretMessage"
          alt="green square with number 9"
          testID="secretMessageIcon"
        />

and use it as your key in the component

	<Icon 
      src={icons[props.name]}
      name={props.name}
      testID={props.testID}
      alt={props.alt}
    />
  1. pass it to styled-components as required.
const Icon = styled.div`
  background-image: url("${props=>props.src}");
  background-repeat: no-repeat;
  width: 200px;
  height: 200px;
  background-color: blue;
  `

END

Comments

Popular posts from this blog

no sound in Papers Please

pdf to png/jpg/etc

Crunchbang Changes