I need to have the componentDidMount method to fire when the Router mounts a component so that a timeout can be started. This timeout eventually sets the state so it can’t be initialized in any render lifecycles or the constructor. I tried changing the Route’s component={Home}
to render={<Home>}
, but then the error render is not a function
comes up. I’m really not sure why this is happening so any help would be greatly appreciated!
App.js render method:
render() {
return (
<BrowserRouter>
<Navbar />
<Container>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
</Switch>
</Container>
</BrowserRouter>
);
}
Home.js:
const Home = (props) => {
const images = [ /* Stuff */ ];
return (
<Stack gap={4}>
<div>
<Card>
<Card.Header>
<ImageRotator images={images} />
</Card.Header>
<Card.Body>
<Card.Title>// A Title</Card.Title>
<Card.Text>
// Text
</Card.Text>
</Card.Body>
</Card>
</div>
</Stack>
);
}
ImageRotator.js:
class ImageRotator extends Component {
constructor(props) {
super(props);
this.state = {
firstImageIndex: 0,
renderImages: false,
imagesShowing: [],
}
}
componentDidMount() {
const imagesShowing = this.calculateImagesToShow(this.state.firstImageIndex);
this.setState({ imagesShowing: imagesShowing });
window.addEventListener('resize', () => {
const imagesToShow = this.calculateImagesToShow(this.state.firstImageIndex);
const imageTimeout = setTimeout(() => this.incrementImageIndex(), 5000);
this.setState({ imagesShowing: imagesToShow, imageTimeout: imageTimeout });
});
}
calculateImagesToShow(firstImageIndex) {
// Returns the images to render on screen
}
resetImageInterval() {
clearTimeout(this.state.imageInterval);
this.setState({ imageInterval: setTimeout(() => this.incrementImageIndex(), 5000) });
}
incrementImageIndex() {
// Increments the state's first image index
}
decrementImageIndex() {
// Decrements the state's first image index
}
render() {
// Renders the calculated images on the screen including two buttons
// which when clicked on call the increment and decrement image index functions
}
}