mpc75
mpc75

Reputation: 989

useState to update h1 text color style in React isn't using the default state

I can't seem to figure out why the color style of my h1 isn't updating to use the default state. It works for my Randy Moss quote default state and works when I switch out the reference to an in-line reference to the color.

function App () {
  const [quote, setQuote] = useState('Nobody controls me but my mama and God.');
  const [textColor, setTextColor] = useState('#DE14F2');

  const updateQuote = () => {
    setQuote(
      Quotes[Math.floor(Quotes.length * Math.random())]
    )
  }

  return (
    <div>
      <div>
        <h1 style={{color: {textColor}}}>{quote}</h1>
      </div>
      <button onClick={updateQuote}>New Quote</button>
    </div>
  );
}

export default App;

Upvotes: 0

Views: 432

Answers (3)

Girgetto
Girgetto

Reputation: 1086

You need to call the method:

<button onClick={() => updateQuote()}>New Quote</button>

also you need to change:

<h1 style={{color: textColor }}>{quote}</h1>

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

For the colour issue, you need to change this way:

<h1 style={{ color: textColor }}>{quote}</h1>

Working CodeSandbox: https://codesandbox.io/s/suspicious-sun-usrht

Upvotes: 1

Karthick
Karthick

Reputation: 381

replace

<h1 style={{color: {textColor}}}>{quote}</h1>

with

<h1 style={{color: textColor}}>{quote}</h1>

Upvotes: 1

Related Questions