Richardson
Richardson

Reputation: 2284

How to extract the the alt value form a jsx image element?

I have this logic where I want to get the alt attribute value of an image element, my first idea way to simply make the value of the key and array that holds a string and image as well ,like this key : ['some string', ] but then I realized I could leverage the alt if this can be possible ?

icons: { 
    iconA: <img style={imgStyle} alt='tool for food' src={iconA} />,
    iconB: <img style={imgStyle} alt='tool for drink' src={ iconB} />,
    }
    
    const convertedObject = useMemo(() => {
    return Object.entries(context.icons).map((e) => ({ equipment: e[1].alt  src: e[1] }));}, []);

Upvotes: 0

Views: 114

Answers (1)

Omar Piga
Omar Piga

Reputation: 306

Try this:

const convertedObject = useMemo(() => {
    return Object.entries(context.icons).map((e) => ({ 
        equipment: e[1].props.alt,
        src: e[1].props.src,
    }));
}, []);

Maybe you want to add "context.icons" to the useMemo dependecy list.

Upvotes: 1

Related Questions