Shaps
Shaps

Reputation: 27

Can't replace value with useState in React

I try to replace the value of a variable when I click on a key but it doesn't work.

↓ This doesn't work but I want it to work

import React, { useState, useEffect } from 'react';

const List = ({ items }) => {

  const [myHTML, setMyHTML] = useState([]);

  function handleKeyPress(e) {
    if (e.key === "e" && window.location.pathname === '/PlayMode') {
      console.log('e pressed');
      setMyHTML([<div><h1>lol</h1></div>]);
    }
  }
  
  if (!document.eventListenerAdded) {
    document.addEventListener("keyup", handleKeyPress);
    document.eventListenerAdded = true;
  }

  return (
    <div>
      {myHTML}
    </div>
  );
};

If I put it in a timeout it works so I don't understand why.

↓ This works but I don't want it like that

import React, { useState, useEffect } from 'react';

const List = ({ items }) => {

  const [myHTML, setMyHTML] = useState([]);

  console.log('starting');
  let myTimeout = setTimeout(() => {
    setMyHTML([<div><h1>pok</h1></div>]);
  }, 2000);
  
  return (
    <div>
      {myHTML}
    </div>
  );
  
};

And I won't put it in a timeout with a 0 delay because I think there is an alternative way right?

Upvotes: 0

Views: 72

Answers (2)

Mani Movassagh
Mani Movassagh

Reputation: 149

better solution and recommended by react

function KeyPressElement() {
    const [toggleHtml, setToggleHtml] = useState(false);

    function handlePresssKey() {
        setToggleHtml( toggleHtml =>!toggleHtml)
        console.log( "You pressed a key." )
    }
    return (       
            <div onKeyDown={() => handlePresssKey()} >
            {toggleHtml&&<div><h1>lol</h1></div>}  
            </div>

    )
}

Reference https://reactjs.org/docs/events.html#keyboard-events

Upvotes: 1

MOLLY
MOLLY

Reputation: 489

You can use useEffect to let it work.

    useEffect(() => {
        setMyHTML([
            <div>
                <h1>lol</h1>
            </div>,
        ])
    }, [])

Full code would be:

const List = ({ items }) => {
    const [myHTML, setMyHTML] = useState([])

    function handleKeyPress(e) {
        if (e.key === 'e' && window.location.pathname === '/PlayMode') {
            console.log('e pressed')
            setMyHTML([
                <div>
                    <h1>lol</h1>
                </div>,
            ])
        }
    }
    useEffect(() => {
        setMyHTML([
            <div>
                <h1>lol</h1>
            </div>,
        ])
    }, [])

    return <div>{myHTML}</div>
}

And you can put your determine statements(if else) in it.

Upvotes: 0

Related Questions