Reputation: 741
In my parent Component:
<div>
<h3>Option <span>{this.state.currentOption + 1}</span> of <span>{this.state.options}</span></h3>
<Button onClick={this.handleOption} variant="primary" type="submit">
{` Next >>`}
</Button>
</div>
I am calling a hook:
handleOption = event => {
event.preventDefault();
let option = this.state.currentOption;
const numOptions = this.state.stackOptions.length;
if (++option >= numOptions) {
option = 0;
}
this.setState({
currentOption: option,
});
}
Which I wish to cycle through an array of objects to render in Canvas:
import React, { useRef, useEffect } from 'react'
const StackRender = props => {
const canvasRef = useRef(null)
useEffect(() => {
const canvas = canvasRef.current
const context = canvas.getContext('2d')
renderOption(props.name, canvas)
}, [])
return <canvas ref={canvasRef} {...props}/>
}
however, the child component (the canvas) doesn't update on the parent state change.
Upvotes: 6
Views: 5845
Reputation: 44880
Add props.name
to the useEffect
dependency array so the function is called whenever props.name
changes:
useEffect(() => {
const canvas = canvasRef.current
const context = canvas.getContext('2d')
renderOption(props.name, canvas)
}, [props.name])
Upvotes: 5