I’m trying to make a hunger indicator, but stroke-dashoffset doesn’t work and the whole code starts glowing red. Can you tell me how to implement this?
<div className="needs-box">
<div className="circle">
<svg className="svg1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink"
width="45" height="64" viewBox="0 0 210 210" >
<circle id="circ" transform="rotate(-90 105 105)" cx="105" cy="105" r="100" style={{strokedashoffset: this.state.drink}} />
</svg>
</div>
</div>```
>Solution :
Here’s an example of how to use the SVG stroke-dasharray and stroke-dashoffset props in React.
The actual effect you want might be different, and could be better implemented with e.g. an SVG arc path.
function Component() {
const [count, setCount] = React.useState(33);
React.useEffect(() => {
const ival = setInterval(() => setCount(c => c + 1), 50);
return () => clearInterval(ival);
}, []);
const perc = count % 100;
const rest = 100 - perc;
return (
<svg viewBox="0 0 200 200" style={{width: "300px"}}>
<circle
cx="100"
cy="100"
r="80"
fill="none"
stroke="red"
strokeWidth="5"
strokeDashoffset={-perc}
strokeDasharray={`${perc} ${perc}`}
/>
</svg>
);
}
ReactDOM.render(<Component />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="root">