soma iyappan
soma iyappan

Reputation: 542

How to backgroundColor key values are map in reactjs?

I need to specify not in array values one Buttons should be in another color using a value in the map .
Is it any possible? I attached my code below.
CodeSandbox box Code

Upvotes: 0

Views: 50

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 10081

You can use some function and check if index is available in queue, show red else blue.

export default function App() {
  var b = ["one", "two", "three", "soma"];
  var que = [1, 2, 3];
  return (
    <div className="App">
      {b.map((text, index) => (
        <>
          <button
            style={{
              backgroundColor: que.some((value) => value === index + 1)
                ? "red"
                : "blue"
            }}
          >
            Button
          </button>
        </>
      ))}
    </div>
  );
}

Better solution:

export default function App() {
  var b = ["one", "two", "three", "soma"];
  const set = new Set([(1, 2, 3)]);

  return (
    <div className="App">
      {b.map((text, index) => (
        <>
          <button
            style={{
              backgroundColor: set.has(index + 1) ? "red" : "blue",
            }}
          >
            Button
          </button>
        </>
      ))}
    </div>
  );
}

Upvotes: 2

BTSM
BTSM

Reputation: 1663

I think you want to implement like this.

import "./styles.css";

export default function App() {
  var b = ["one", "two", "three", "soma"];
  var que = [1, 2, 3];
  return (
    <div className="App">
      {b.map((text, index) => (
        <>
          <button
            style={{
              backgroundColor: que.filter((value) =>
                value === index + 1).length ? "red" : "blue"
            }}
          >
            Button
          </button>
        </>
      ))}
    </div>
  );
}

This is codepen URL https://codesandbox.io/s/sleepy-darwin-4po149?file=/src/App.js:0-415

Upvotes: 1

Related Questions