Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. First, create a state variable that holds the text color.

  2. Next, define a function that will update the state variable based on some condition. For example, if the background color of an element changes to a certain color, the text color should change to a contrasting color.

  3. Use the state variable to set the style attribute of the text element.

  4. Use an event listener to listen for changes to the condition that triggers the text color change, and call the function that updates the state variable.

  5. Whenever the state variable is updated, the text color will change automatically.

Example code:

import { useState } from 'react';

function MyComponent() {
  const [textColor, setTextColor] = useState('black');

  function updateTextColor() {
    // logic to determine new text color based on some condition
    setTextColor('white');
  }

  return (
    <div style={{backgroundColor: 'red'}} onClick={updateTextColor}>
      <p style={{color: textColor}}>Hello, world!</p>
    </div>
  )
}