Home > Enterprise >  set childNodes dynamicly styles with array of colors in reactjs
set childNodes dynamicly styles with array of colors in reactjs

Time:08-22

I want to give each div or childNodes a different color using an array of colors But only the last color of the array is given to all the divs or childNodes.

Can you tell me how we can dynamically style them by mapping or forEach nodes,childNodes,dives and colors in reactjs?

you can see demo: codesandbox link

const containerRef = useRef()

    useEffect(()=>{
        containerRef.current.childNodes.forEach(item=>{
          ['green','blue','green','yellow','orange'].map(colors => {
            item.style.background = colors 
         })
        })
      })


    <div 
          ref={containerRef }
          className="h-96 w-full flex items-center gap-x-6 border border-black">
            <div className='w-20 h-20 border border-black'>one</div>
            <div className='w-20 h-20 border border-black'>two</div>
            <div className='w-20 h-20 border border-black'>three</div>
            <div className='w-20 h-20 border border-black'>four</div>
            <div className='w-20 h-20 border border-black'>five</div>
          </div>

CodePudding user response:

You don't need map the colors, you just need to assign each element with a corresponding index of color.

import "./styles.css";
import React, { useEffect, useRef } from "react";

export default function App() {
  const containerRef = useRef();
  const colors = ["green", "blue", "green", "yellow", "orange"];

  useEffect(() => {
    containerRef.current.childNodes.forEach((item, i) => {
      item.style.background = colors[i];
    });
  });
  return (
    <div ref={containerRef} className="container">
      <div>one</div>
      <div>two</div>
      <div>three</div>
      <div>four</div>
      <div>five</div>
    </div>
  );
}

live demo

CodePudding user response:

Here you're mapping again on colors, for each item in child nodes which results in assigning the last color to each div.

You will have to use the index of the item in the childNodes list, and access the color of that index from the colors array.

CodeSanbox Link - https://codesandbox.io/s/fragrant-frost-3v0v76

  • Related