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?
>Solution :
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.