I am creating an animation on scroll
from an svg but with react
and I have the following question, is there any way to pass this dynamic css rule from js
:
line.style.strokeDasharray
so that it can be added in react?
class App extends React.Component {
constructor(props) {
super(props);
this.line = React.createRef();
}
componentDidMount = () => {
let line = this.line.current;
let lengthLine = line.getTotalLength();
line.style.strokeDasharray = lengthLine; // Alli iria
}
render() {
return (
<div className="App">
<div className="header-previus">
<h1>Scroll down to show the magic</h1>
</div>
<svg width="149" height="562" id="delgada-linea" viewBox="0 0 149 562" fill="none" xmlns="http://www.w3.org/2000/svg">
<path ref={this.line} d="M1 1C25.6599 75.33 143.5 121 113.5 192.5C83.5 264 -22.5 320.5 18.5 378C59.5 435.5 185 495.5 137 560.5" stroke="black" strokeWidth="2"/>
</svg>
</div>
);
}
}
my css:
.App
& > .header-previus
height: 800px
width: 100%
background: lightblue
& > h1
color: #fff
I think you are combining as the styles are defined in
React
to as defined incss
. When you're doingline.style.strokeDasharray = lengthLine;
this you're trying to access the propertystrokeDasharray
the wayReact
it references styles (without hyphens and with camelCase), but you have to remember that by using the direct reference of theDOM
you're trying to access thecss
in its actual form in which the property name would bestroke-dasharray
.Since it's hyphenated you'll need to use square bracket notation to access your property on the object, like so:
I want to add that there are better ways to do this depending on what you want to do in your implementation and if you are learning you should use functional and
hooks
.Hope this helps, good luck programming.
As a demonstration that the code works correctly and you can change the property dynamically, you can change the one
componentDidMount
in your code to this:You will see how the property is changed dynamically.