importing images with React

basic image import with React

Mon, 01 Oct 2018

I’m teaching a friend how to code and this was one of the various topics that I wanted to teach him. This isn’t going to be fancy, just a very simple import for an image using React. Lets start out with super simple html. When you want to add a picture to a website you would write a simple line such as this

<img src=“smiley.gif" alt="Smiley face">

The name of the tag is “img”, the “src” attribute is the physical location of the file relative to where our current file is and “alt” attribute is a short description of the picture that is with screen readers. That is the basic structure of an image tag. With React, the same structure applies, there are just two changes between how you would add images with html and how you add pictures with React.

  1. You need to import the picture into the React component. Say our image is in the same folder as our React component, your import would look something like this.

    import Logo from./logo.png”;

    This will import the file logo.png and reference in the file as “Logo”. Now when you reference the img tag in project you want it to now look like this

    <img src={Logo}>
  2. Next up, all React components and html tags need to be closed. Instead of your img tag ending with a “>”, it now needs to end with a “/>”. This lets React now that the tag is closed and that are no children within the tag.

Putting it all together

With both step 1 and 2 implemented, your image tag should now look like this.

<img src={Logo} alt=“website logo” />
Buy Me A CoffeeDigitalOcean Referral Badge
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge