Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
set childNodes dynamicly styles with array of colors in reactjs

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>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!