Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Typescript: Object is possibly 'null' by get the input value with html element id

I code with next.js a login:

import type { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Router from 'next/router'
import * as React from 'react'

const Home: NextPage = () => {

  const [disable, setDisable] = React.useState(false);

  const loginUser = async (e: any) => {
    try {

      setDisable(true)

      const y = (window.document.getElementById('inputUsername'))

      let inputValue = window.document.getElementById('inputUsername').value

      console.log(inputValue)

      const resp = await fetch('/api/token/valid')
      const data = await resp.json()
      if (data.token) {
        //Router.push('/dashboard')
        setDisable(false)
      }
    } catch (err) {
      // Handle Error Here
      console.error(err);
    }
  };

  return (
    <div className={styles.container}>
      <Head> 
        <title>Login - Uhrenlounge CMS</title>
        <meta name="description" content="Generated by create next app" />
      </Head>

      <main className={styles.main}>
        <form className="p-3 mb-2 bg-secondary text-white">
            <div className="text-center">
                <h1>Uhrenlounge CMS</h1>
            </div>
            <hr />
            <div className="mb-3">
                <label className="form-label">Benutzername</label>
                <input 
                  type="text" 
                  className="form-control" 
                  id="inputUsername" 
                  name="inputUsername" 
                  placeholder="Benutzername" 
                  required 
                  />
            </div>
            <div className="mb-3">
                <label className="form-label">Passwort</label>
                <input type="password" className="form-control" id="inputPassword" placeholder="Passwort" />
            </div>
            <div className="d-grid gap-2">
                <button type="button" disabled={disable} onClick={loginUser} className="btn btn-primary" id="btnLoginUser">Login</button>
            </div>
        </form>
      </main>
    </div>
  )
}

export default Home

I want to get the value of inputs after the click on the button. I try to get the value with this code:

let inputValue = window.document.getElementById('inputUsername').value

VSCode give me this error: Object is possibly 'null'.

I don't know what can i do. Does anyone have any idea or explanation how to access the value after onclick?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's just telling you that if there is no element with id 'inputUsername' getElementById will return null instead of the value you are expecting.

You can handle or ignore that case as you see fit.

However if you really need to access dom nodes in react the right way to do it is hooks https://reactjs.org/docs/hooks-intro.html. Right now your component may not work if two exist at the same time due to the overlapping ids.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda