I'm working on a carousel in React JS which currently is rendering a set of numbers:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import {
Wrapper,
NumbersWrapper,
NumbersScroller,
NumberText
} from "./Numbers.style";
const hundred = new Array(100)
.fill(0)
.map((k, v) => ({ key: v, label: v + 1 }));
class Carousel extends Component {
constructor(props) {
super(props);
this.state = {
activeNumber: 0
};
}
setActiveNumber(number) {
this.setState({
activeNumber: number
});
}
render() {
const { activeNumber } = this.state;
const intAciveNumber = Number(activeNumber);
return (
<Wrapper>
<NumbersWrapper
onClick={() => this.setActiveNumber(intAciveNumber + 1)}
>
<NumbersScroller
style={{
left: `${130 - intAciveNumber * 55}px`
}}
>
{hundred.map(({ key, label }) => {
const isNeighbor =
key + 1 === activeNumber || key - 1 === activeNumber;
const isActive = key === activeNumber;
return (
<NumberText
key={key}
isNeighbor={isNeighbor}
isActive={isActive}
>
{label}
</NumberText>
);
})}
</NumbersScroller>
</NumbersWrapper>
</Wrapper>
);
}
}
export default Carousel;
Now I'd like to use display custom numbers from an array like this example using the new keyword:
const hundred = new Array([100, 150, 200, 250, 400, 500, 650, 780, 830, 900, 1500])
.fill(0)
.map((k, v) => ({ key: v, label: v }));
However, when I make this change to the array, nothing happens. How can I correctly display the values inside of the component? If there is an NPM library that does this for React (web), I would take that as a solution also. Thanks in advance.
I have been using this a lot: https://react-slick.neostack.com/
Works like a charm - and very customizable.
Something along the lines of this would probably work..
import React, { Component } from "react";
import Slider from "react-slick";
export default class SimpleSlider extends Component {
render() {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
};
return (
<div>
<h2> Single Item</h2>
<Slider {...settings}>
{hundred.map(({label}) => (
<div>
{label}
</div>
))}
</Slider>
</div>
);
}
}
You need to pass the values as separate parameters instead of an array like so.
const hundred = new Array(100, 150, 200, 250, 400, 500, 650, 780, 830, 900, 1500)
.fill(0)
.map((k, v) => ({ key: v, label: v }));
Right now, you are creating an array within the hundred array at position zero, so when you iterate over the objects with .map, you are only going over a single value, which contains the whole array.
Output of your current implementation of array initialization:
