Home  >  Q&A  >  body text

Color variable changes for each mapped item Tailwind reacts

I want that once I add another item to the list, the color of the previous item should not change

const NoteItem = ({ note }) => {
  const { colors, randomColorFunction } = useContext(AppContext);
  const color = randomColorFunction(colors);
  return (
    <div
      className={`flex flex-col min-h-28  py-6 justify-between px-3 rounded-md whitespace-pre-wrap break-words`}
      style={{ backgroundColor: `${color}` }}
    >
      <span className="font-bold text-3xl">{note.title}</span>
      <span>{note.content}</span>
      <small className="text=xl">{note.date}</small>
    </div>
  );
};

P粉982009874P粉982009874221 days ago457

reply all(1)I'll reply

  • P粉237125700

    P粉2371257002024-04-04 18:40:53

    You can solve this problem in two ways

    1. Use citation

    import { useRef } from "react";
    
    const NoteItem = ({ note }) => {
      const { colors, randomColorFunction } = useContext(AppContext);
      const color = useRef(randomColorFunction(colors));
    
      return (
        
    ...
    ); };

    2.Usage status

    import { useState } from "react";
    
    const NoteItem = ({ note }) => {
      const { colors, randomColorFunction } = useContext(AppContext);
      const [color] = useState(randomColorFunction(colors));
    
      return (
        
    ...
    ); };

    If you don't want to change the color, I think useRef is more appropriate.

    See hereLive preview

    reply
    0
  • Cancelreply