Home > Mobile >  How to use Refs to change image src in React js
How to use Refs to change image src in React js

Time:04-24

I'm trying to change an image src using refs instead of document.querySelector, But i can't figure out how to go about it and can't find a tutorial/documentation for it.

 <img id='indigo' src={igo} height="134" width="130" />

                          let img = document.querySelector('indigo');
                          if(reasultl === 'true'){
                          
                          img.src = {igo}
                        }
                         else{
                          img.src = {placeholder}
                         }

Thanks

CodePudding user response:

first create ref for image tag using this way

in class component

const imagRef=React.createRef();

in functional component

const imageRef=useRef();

assign it to image tabg like this

<img src={igo} ref={imageRef} />

and use imageRef to change the src like this

       if(reasultl === 'true'){
             imageRef.current.src = {igo}
       }
       else{
          imageRef.current.src = {placeholder}
     }

however i this can be done without refs,as shown in armans's answer. lets do this with state in functional component

        import { useEffect, useState } from "react";
        import "./styles.css";

        export default function App() {
        const [loading, setLoading] = useState(true);
        const [image, setImage] = useState(
          "https://c.tenor.com/I6kN-6X7nhAAAAAj/loading-buffering.gif"
        );
        useEffect(() => {
          if (loading === true) {
            setTimeout(() => {
              if (loading === true) {
                setLoading(false);
                setImage(
                  "https://post.healthline.com/wp-content/uploads/2020/08/3180-Pug_green_grass-732x549-thumbnail-732x549.jpg"
                );
              }
            }, 1000);
          }
        }, [loading, setLoading, setImage]);

        return (
          <div className="App">
            <img src={image} alt="okay" />
          </div>
        );
        }

try here in sandbox

now do the same using refs

        import { useEffect, useState, useRef } from "react";
        import "./styles.css";

        export default function App() {
          const [loading, setLoading] = useState(true);
          const imageRef = useRef();
          useEffect(() => {
            if (loading === true) {
              setTimeout(() => {
                if (loading === true) {
                  setLoading(false);
                }
              }, 1000);
            }
          }, [loading, setLoading]);
          useEffect(() => {
            if (loading === true) {
              imageRef.current.src =
                "https://c.tenor.com/I6kN-6X7nhAAAAAj/loading-buffering.gif";
            } else {
              imageRef.current.src =
                "https://post.healthline.com/wp-content/uploads/2020/08/3180-Pug_green_grass-732x549-thumbnail-732x549.jpg";
            }
          }, [loading, imageRef]);
          return (
            <div className="App">
              <img ref={imageRef} alt="okay" />
            </div>
          );
        }

try it in sandbox

hope this will help.

CodePudding user response:

Instead of changing the source attribute this way you can use react hook's useState. e.g

import {useState} from 'react';

const [source,setSource] = useState("");

 if(reasultl === 'true'){
    setSource(igo}
   }else{
    setSource(placeholder)
   }

<img id="indigo" src={source} height="134" width="130" />

CodePudding user response:

import your images at the top

import image1 from "../your image path/mountain.jpg"
import image2 from "./images/lake.png"

then use the images as variables by adding them to a useState() like Arman said,or coditionaly render the proper image in return()

return (
    {"your true/false condition" ? <img src={image1}/> : <img src={image2}/>}
)

dont put the images in public but in src

  • Related