i'm having a problem using Materialize-CSS carousel. The standard way to create the carousel is :
<div class="carousel">
<a class="carousel-item" href="#one!"><img
src="https://lorempixel.com/250/250/nature/1"></a>
<a class="carousel-item" href="#two!"><img
src="https://lorempixel.com/250/250/nature/2"></a>
<a class="carousel-item" href="#three!"><img
src="https://lorempixel.com/250/250/nature/3"></a>
</div>
But I want to create a carousel item for every item in an array named "products" hence i'm trying this code in the JSX :
<div className="carousel">
{generalStore.products.map(p =>
<a className="carousel-item"><img src={p.pic} /></a>)}
</div>
p,pic == image url
But this returns an error :
TypeError: Cannot read property 'clientWidth' of undefined
Ant ideas to solve this? Thanks
It can be implemented in materializeCSS also.
For this, you need to do npm install materialize-css@next
. After this, you need to import the materialize-css in your component JS file.
To use the Javascript materialize-css components, a reference of these components has to be made in componentDidMount()
has to be made and then it can be used in ref
.
import React, { Component } from "react";
import M from "materialize-css";
import "materialize-css/dist/css/materialize.min.css";
import data from "./data.json";
class Carousel extends Component {
componentDidMount() {
const options = {
duration: 300,
onCycleTo: () => {
console.log("New Slide");
}
};
M.Carousel.init(this.Carousel, options);
}
renderThis = () => {
return data.map(i => (
<a key={i.url} className="carousel-item">
<img src={i.url} />
</a>
));
};
render() {
return (
<div
ref={Carousel => {
this.Carousel = Carousel;
}}
className="carousel"
>
{this.renderThis()}
</div>
);
}
}
export default Carousel;