Popa Laris
Popa Laris

Reputation: 23

ReactJs - Display components around a component

I want to display a specific number of components around a component. How can I do that? :)

With this implementation, I draw 8 Patrat component

{Array.from(Array(8)).map((item, index) =>
    (<Patrat key={index}/>)
)}

I want to display these 8 Patrat around a circle which is also a component.

Upvotes: 2

Views: 476

Answers (3)

Dwarka Tiwari
Dwarka Tiwari

Reputation: 185

After Understanding the issue and what you want here is the final solution

You can also create function which can dynamically create position and pass it to the Child components

Here is complete code resource link (Click Here)

Also your can experiment with some comment line in code link given above

Upvotes: 2

Kocik
Kocik

Reputation: 504

You could make the circle responsible for positioning the elements, then have Patrats as children of circle (Circle > div.circle_element_position > Patrat) or if Patrats will change depending on the parent component, you could use same logic but use renderProps for Patrats (Circle > div.circle_element_position > props.renderPatrat(index))

It would look more or less like this:

function Partat()  {
   return <div>1</div>
}

function calculatePositions(numberOfPatrats) {
     //your implementation
}

function Circle ({numberOfPatrats}) {
       let positions = calculatePositions(numberOfPatrats);

       return <div className="circle">
            {positions.map(
                (position, index) => <div style={position} key={index}><Partat /></div>
            )}
       </div>
}

To place Parats on the positions you want you just need to implement calculatePositions, which will be similar to what you had in your jsfiddle example.

Upvotes: 0

Tholle
Tholle

Reputation: 112777

You could create a recursive loop where you create a new Patrat component with the recursive call as children to it.

Example

function Patrat({ children }) {
  return (
    <div
      style={{
        paddingLeft: 10,
        backgroundColor: "#" + Math.floor(Math.random() * 16777215).toString(16)
      }}
    >
      {children}
    </div>
  );
}

function App() {
  const content = (function patratLoop(num) {
    if (num === 0) {
      return <div> Foo </div>;
    }
    return <Patrat>{patratLoop(--num)}</Patrat>;
  })(8);

  return content;
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 0

Related Questions