Home > Enterprise >  How can i give a url to a react components using props?
How can i give a url to a react components using props?

Time:09-14

Component structure's

const IconSkill = (props) => {
      return (
        <img
        onm ouseOver={() => {
          const skillIcon = document.getElementById("skills-icon");
    
          skillIcon.classList.add("skills-icon-hover");
          setTimeout(() => {
            skillIcon.classList.remove("skills-icon-hover");
          }, 1500);
        }}
        id="skills-icon"
        className="skills-icon"
        src={require(props.srcUrl).default}
        alt={props.alt}
      />
      )
    }

Here you see that i am trying to give a relative URL to src img using props, and it isn't working:

  <IconSkill srcUrl={"../../images/skills/figma.svg"} alt="HTML Icon" />

Here console log error:

react-refresh-runtime.development.js:315 Uncaught Error: Cannot find module '../../images/skills/figma.svg'

CodePudding user response:

try to import it by giving some random name if its under "src" folder:

import ImageName form "../../images/skills/figma.svg";
export default function(){
 return  <IconSkill srcUrl={ImageName} alt="HTML Icon" />
}

If images is under public folder -> images folder then your code should be:

<IconSkill srcUrl={"./images/skills/figma.svg"} alt="HTML Icon" />

and on IconSkill Component:

const IconSkill = (props) => {
  return (
    <img
    onm ouseOver={() => {
      const skillIcon = document.getElementById("skills-icon");

      skillIcon.classList.add("skills-icon-hover");
      setTimeout(() => {
        skillIcon.classList.remove("skills-icon-hover");
      }, 1500);
    }}
    id="skills-icon"
    className="skills-icon"
    src={props.srcUrl}
    alt={props.alt}
  />
  )
}

CodePudding user response:

Your code is generally not a React code. To achieve what you want your code must look smth like this.

import {useState} from "react";

const IconSkill = (props) => {
const {alt, srcUrl} = props;

//you need some state to control it's hover state

const [skillsIcon, setSkillsIcon] = useState(false);


const handleHover = () => {

setSkillsIcon(true);
setTimeout(() => {
        setSkillsIcon(false);
      }, 1500);
}

return (
       <img 

onMouseOver={handleHover} 
src={srcUrl} 
className={skillsIcon ? "skills-icon-hover" : null}
id="skills-icon"
alt={alt}
/>
)
}
  • Related