Home > Back-end >  Cant replace value with useState in React
Cant replace value with useState in React

Time:12-26

I try to replace the value of a variable when I click on a key but it doesnt work. ↓ this dont 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 work so I dont understand why. ↓ this work but i dont 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 wont put it in a timeout with a 0 delay because I think there is an alternative right ?

CodePudding user response:

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

CodePudding user response:

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.

  • Related