简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM