B
B
bacca2018-05-04 02:54:32
React
bacca, 2018-05-04 02:54:32

How to do conditional rendering in react?

Good afternoon, I'm looping around an array of data? you need to wrap every 3 slides in a new "row". please tell me how to implement this.
{slides.map((slide, index ) => (
index !== 0 &&index % 3 === 2) ? : ''
"component" Item
key={index}
data={slide}
/ "closeComponent"
slides. length=== index + 1 || index % 3 === 1 ? : ''
))}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-05-04
@bacca

const rows = slides.reduce((acc, el, i) => {
  if(i % 3 === 0) acc.push([]);
  acc[acc.length-1].push(el);

  return acc;
}, []);

return (
  <Wrapper>
    {rows.map((row, index) => (
      <Row key={index}>
        {row.map((slide, i) => <Slide key={i} data={slide} />)}
      </Row>
    ))}
  </Wrapper>
);

C
Coder321, 2018-05-04
@Coder321

function createWrappedSlides(slides, count = 3) {
    const wrappedSlides = [];
    for (let i = 0; i < slides.length; i += count) {
        wrappedSlides.push(slides.slice(i, i + count));
    }
    return wrappedSlides;
}
 createWrappedSlides(slides).map((slide, i) => <Slide key={i} data={slide} />)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question