3

I want to dynamically attach color to my react component

These are the colors I want to attach

  this.color = ["#E91E63", "#2196F3", "#FDD835"]

I am mapping an array in JSX (sort of like this)

   { this.state.graphData.map(data => {
        (<VictoryArea name="area-1" data={data} style={{ data: { fill: "#E91E63" } }}/>)
    })}

My mapped array have 6 elements.

I want element 1 and element 4 to have same color, 2 and 5, 3 and 6.

Question: Can someone please help me in figuring out how I can attach dynamic color in fill?

1 Answer 1

2

You can use the second argument of the map function which is the index of the element, along with the % operator to get the color dynamically.

{this.state.graphData.map((data, index) => 
  <VictoryArea
    name="area-1"
    data={data}
    style={{ data: { fill: this.color[index % this.color.length] } }}
  />
)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.