Home > Blockchain >  Array.map() creates a new line for every element it creates
Array.map() creates a new line for every element it creates

Time:01-19

I'm creating a demonstration of the concept of polyrhythms as a proof-of-concept project for my React learning. I have the following as a function right now:

  const [value, setValue] = useState("");
  const [value2, setValue2] = useState(""); // I will extrapolate out to n switches
  const beatArr = [];                       // when I have the rest of the functionality
  for (var i = 1; i <= value; i  ) {        // implemented.
    beatArr.push(i);
  }
  const beats = beatArr.map((x) => <Beat key={x} identifier={x} />);

I have two components thus far; a <Switch /> (used to pull information from the DOM) and a <Beat /> (takes the switches' value and renders that many beats).

My issue as it stands right now is that using beatArr.map(...) creates a new line after every <Beat /> element, and I want it to not do that. For example with a value of 4 and three groupings of elements, right now it renders as:

1 1 1
2 2 2
3 3 3
4 4 4

While I want it to render as:

1 2 3 4
1 2 3 4
1 2 3 4

How can I refactor this into something that could make it work? Is this an issue with the .map() method? I have used CSS to add line breaks in between the groups, but the result as of now is:

1
2
3
4
1
...

Thanks in advance, you guys are great.

EDIT: Forked at current point for future-proofing this question; here is current source.

CodePudding user response:

Simple solution is change you element to element in Beat component

import React from "react";

function Beat({ identifier }) {
  return <span className="beat-elem">{identifier}</span>;
}

export default Beat;

https://codesandbox.io/s/polyrhythm-demonstration-forked-bpgdp?file=/src/Beat.js

CodePudding user response:

In your <Beat> component, if you use a <span> instead of <div>, it should work.

function Beat({ identifier }) {
return <span className="beat-elem">{identifier}</span>;
}
  •  Tags:  
  • Related