Home > Software design >  How do I pass images as props in React typescript react function component export?
How do I pass images as props in React typescript react function component export?

Time:11-26

I am trying to import and pass an image as a prop to my Skill component from my Skills.tsx file. The image path is the following:

public/images/skill-logos/html.png.

Here is what my Skills.tsx file looks like:

import React from 'react';
import Skill from './Skill';
import HtmlLogo from '../public/image/skill-logos/html.png';

function Skills({}: Props) {
  return (
    <div>
        <h3>Skills</h3>
        <h3>Hover over a skill for current proficiency</h3>
        <div>
            <Skill 
              imageSource={HtmlLogo} 
              proficiency="80"
            />
        </div>
    </div>
  );
};


export default Skills;

And this is what my Skill.tsx file looks like:

import React from 'react';

type Props = {
    imageSource: string;
    proficiency: string;
};

function Skill({ imageSource, proficiency }: Props) {
    return (
        <div>
            <img 
                src={imageSource}
                alt='' 
            />
            <div>
                <p>{proficiency}%</p>
            </div>
        </div>
    );
};

export default Skill;

So far, it does not render the image, but it does render the proficiency.

So far i've tried using require('image_path') to import the image, but it didn't work. If anyone knows which method works, I would highly appreaciate it.

CodePudding user response:

When you want to use an image from public directory, you should not use import.

Instead, you should do this:

import React from 'react';
import Skill from './Skill';

const HtmlLogo = process.env.PUBLIC_URL   "/image/skill-logos/html.png";

function Skills({}: Props) {
  return (
    <div>
        <h3>Skills</h3>
        <h3>Hover over a skill for current proficiency</h3>
        <div>
            <Skill 
              imageSource={HtmlLogo} 
              proficiency="80"
            />
        </div>
    </div>
  );
};


export default Skills;

Read more here.

CodePudding user response:

Just add the path directly to the prop value

<Skill 
  imageSource={"./images/skill-logos/html.png"} 
  proficiency="80"
 />
  • Related