Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Refs to change image src in React js

Tags:

reactjs

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

like image 397
jay Avatar asked Oct 18 '25 13:10

jay


1 Answers

First, create ref for image tag using this way

  • in class component:

    const imagRef=React.createRef();

  • in functional component:

    const imageRef=useRef();

Then, assign it to image tab like this

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

After that, use imageRef to change the src like this:

imageRef.current.src = result === 'true' ? {igo} : {placeholder}

However i this can be done without refs, as shown in armans's answer.

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) {
        setTimeout(() => {
            if (loading) {
                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

Finally, 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) {
            setTimeout(() => {
                if (loading) {
                    setLoading(false);
                }
            }, 1000);
        }
    }, [loading, setLoading]);

    useEffect(() => {
    imageRef.current.src = loading ?
        "https://c.tenor.com/I6kN-6X7nhAAAAAj/loading-buffering.gif" :
        "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!

like image 155
Jatin Parmar Avatar answered Oct 20 '25 02:10

Jatin Parmar