Home > Blockchain >  How to backgroundColor key values are map in reactjs?
How to backgroundColor key values are map in reactjs?

Time:05-23

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

CodePudding user response:

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>
  );
}

CodePudding user response:

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

  • Related