Pavel Fedorovsky
Pavel Fedorovsky

Reputation: 57

React state changes, but component doesn't rerender

I have svg and when I click on it, a line is added:
line:

const Line = (props) => {
    const { x1, y1, x2, y2, scale } = props

    return (
        <line x1={x1 * scale} y1={y1 * scale} x2={x2 * scale} y2={y2 * scale}
            style={{ stroke: "black", strokeWidth: 3, strokeLinecap: "round" }}></line>
    )
}

This is how I add lines (100, 100, 200, 200 are just sample numbers):

setContent([...content, <Line key={'line' + svgRef.current.childElementCount} scale={params.scale} x1={100} y1={100} x2={200} y2={200} />])
<svg>
    {content}
</svg>

But when the params.scale changes, the component doesn't rerender.
This is how i change the state (multiplier is a float number):

setParams({...params, scale: params.scale * multiplier})

Upvotes: 0

Views: 106

Answers (1)

Ali Sattarzadeh
Ali Sattarzadeh

Reputation: 3559

I think the problem would be from setting content you set content state and it won't be reset per se by changing param state

I think you need to use useEffect and params.scale as dependency

sth like this :

useEffect(()=>{
  setContent([...content, <Line key={'line' + 
     svgRef.current.childElementCount} scale={params.scale} x1={100} y1= 
      {100} x2={200} y2={200} />])

},[params.scale])

Upvotes: 1

Related Questions