How Can You Instantiate A .gif File In A React App?
Solution 1:
Please, try this one.
functionApp() {
const [stars, setStars] = useState(0);
return (
<React.Fragment><ponClick={() => setStars((s) => s + 1)}>+</p>
{new Array(stars).fill().map((s, ind) => {
return <Starkey={ind}></Star>;
})}
<ponClick={() => setStars((s) => (s === 0 ? 0 : s - 1))}>-</p></React.Fragment>
);
}
exportfunctionStar(props) {
const [id] = useState(Math.random()); // Generate unique id for this itemreturn (
<imgclassName="icon"src={`${process.env.PUBLIC_URL}/once-star-filled.gif?id=${id}`}
alt="animated star"
/>
);
}
I fix some notation errors, like function name should be started from small letter.
Moreover, you could use only one state to store and render stars gif.
Also, it is better to create another React function element <Star />
. In this way you can reuse this gif later, and add some props, for instance different alter text
, src attribute
and et al.
[Update 1]
I disagree with @Karl comment, there is a significant flaw in his solution: when the src
is formed using the ind
, elements will be animated only once (ex: remove element with ind=2
and add again element with ind=2
give us a static image).
So I decided to supplement my answer with one more option, which I would not use in production, but it is interesting and solves the OP's problem.
What is the new solution? We fetch the image through fetch
, convert it to dataUrl
, delete the first part represented metadata
, and pass it to the Star elements for rendering as src
props.
Each element adds meta-information with its own Id, which does not affect the file itself, but the browser perceives the picture as new. Therefore, all start animates every time their appear on page.
importReact, { useState, useRef } from"react";
import"./App.css";
functionApp() {
const [stars, setStars] = useState(0);
const [data, setData] = useState(null);
const ref = useRef(null);
React.useEffect(() => {
fetch("./ezgif-2-110436c6c12b.gif")
.then((res) => res.blob())
.then(async (text) => {
const reader = newFileReader();
reader.onload = (ev) => {
setData(
ev.currentTarget.result.replace("data:image/gif;base64", "")
);
};
reader.readAsDataURL(text);
});
}, []);
return (
<React.Fragment><ponClick={() => setStars((s) => s + 1)}>+</p>
{data &&
new Array(stars).fill().map((s, ind) => {
return <Starsrc={data}key={ind}></Star>;
})}
<ponClick={() => setStars((s) => (s === 0 ? 0 : s - 1))}>-</p></React.Fragment>
);
}
/**
*
* @param {{src: string}} props
* @returns
*/exportfunctionStar(props) {
const [id] = useState(Math.random());
return (
<imgclassName="icon"src={`data:image/gif;base64;${id}` + props.src}
alt="animated star"
/>
);
}
exportdefaultApp;
Post a Comment for "How Can You Instantiate A .gif File In A React App?"