Home > Mobile >  Conditionally Rendering Image Source based on Returned value from Database
Conditionally Rendering Image Source based on Returned value from Database

Time:07-09

Trying to wrap my head around what the process would be to change an image source depending on the value of what is returned from the database.

Snippet:

function KnifesComponent() {

  const knifeCollection = collection(db, "knives");
  const [knives, setKnives] = useState([]);
  
  useEffect(() => {
    onSnapshot(knifeCollection, (snapshot) => {
      setKnives(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    });
  }, []);  

  return (
      {knives.map((skin) => {
        return (
           {skin.rarity} // Returns "Ultra" for Example
           <div><img src={isUltra : require('../../public/Rarity_Ultra.png')}></div>
           
  );
}

I was thinking of making a const with all the values in and then using as needed but not sure how exactly to approach it

  const rarities = {
    Exclusive: require('../../public/Rarity_Exclusive.png'),
    Ultra: require('../../public/Rarity_Ultra.png'),
  }

What is the proper way to conditionally format different images based on values?

CodePudding user response:

You can change the rarities object to this (paths as values):

const rarities = {
  Exclusive: '../../public/Rarity_Exclusive.png',
  Ultra: '../../public/Rarity_Ultra.png',
}

Then you can then access the image from the object by rarity.

function KnifesComponent() {

  const knifeCollection = collection(db, "knives");
  const [knives, setKnives] = useState([]);
  
  useEffect(() => {
    onSnapshot(knifeCollection, (snapshot) => {
      setKnives(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
    });
  }, []);  

  return (
    {
      knives.map((skin) => {
        return (
          {skin.rarity} // Returns "Ultra" for Example
          <div>
            <img src={require(rarities[skin.rarity])}>
          </div>
        );
      })     
    }
  );
}

The object also can be like this (just the image names):

const rarities = {
  Exclusive: 'Rarity_Exclusive.png',
  Ultra: 'Rarity_Ultra.png',
}

And access them:

<img src={require(`../../public/${rarities[skin.rarity]}`)}>
  • Related