Home > OS >  How do you pass an image from the root component to a child component using state variables in React
How do you pass an image from the root component to a child component using state variables in React

Time:06-09

I'm having issues passing an image from my root component (App.js) to my child component (PokemonCard.js). I'm able to successfully pass Strings, but images never work.

The picture below shows my setup.

PICTURE: https://i.stack.imgur.com/8P819.png

App.js file

import PokemonCard from "./components/PokemonCard";

function App() {

   const [pokeName, setPokeName] = useState("");

   const [pokeImage, setPokeImage] = useState("");

   const [pokeAttack, setPokeAttack] = useState("");

   setPokeName("Bellsprout");
   setPokeImage("bellsprout.png");
   setPokeAttack("25");

   return (
       <div>
           <PokemonCard name={pokeName} image={pokeImage} attack={pokeAttack} />
       </div>
   );

PokemonCard.js

const PokemonCard = (props) => {
    return (    
        <div>
            <h1>{props.name}</h1>
            <img src={require (`../assets/${props.image}`)} />
            <h1>{props.attack}</h1>
        </div>
    );
}

export default PokemonCard;

Anytime an image is passed, the entire program breaks and I'm left with a blank screen. Any advice is appreciated!

CodePudding user response:

Please try do this.

import PokemonCard from "./components/PokemonCard";
import bellsprout from './assets/bellsprout.png"

function App() {

   const [pokeName, setPokeName] = useState("");

   const [pokeImage, setPokeImage] = useState("");

   const [pokeAttack, setPokeAttack] = useState("");

   setPokeName("Bellsprout");
   setPokeImage(bellsprout);
   setPokeAttack("25");

   return (
       <div>
           <PokemonCard name={pokeName} image={pokeImage} attack={pokeAttack} />
       </div>
   );

PokemonCard

const PokemonCard = (props) => {
    return (    
        <div>
            <h1>{props.name}</h1>
            <img src={props.image} />
            <h1>{props.attack}</h1>
        </div>
    );
}

export default PokemonCard;

CodePudding user response:

I would use import instead of require and maybe move it to a separate function:

const PokemonCard = (props) => {
    const { image } = props;

    const [img, setImg] = useState(); 

    useEffect(() => {
       import(`../assets/${image}`).then(img => {
           setImg(img.default);
       });
    ), [image]);
    return (    
        <div>
            <h1>{props.name}</h1>
            {img && <img src={img} />}
            <h1>{props.attack}</h1>
        </div>
    );
}

export default PokemonCard;
  • Related