This is my code, but I can’t get it to work, i’m using react and typescript(i’m new to both), i don’t know what i’m doing wrong, it always says: Uncaught TypeError: Cannot read properties of null(reading ‘value’). What I did wrong?
==================================/ /============================
import { Button } from "./components/ui/button"
import { Input } from "./components/ui/input"
function App() {
const inputElement = document.getElementById('bla') as HTMLInputElement.value;
console.log(inputElement)
return (
<>
<div className="p-6 space-y-6">
<div className="flex justify-center">
<div className="flex justify-between w-1/2">
<h1 id="bla">bla bla bla</h1>
<Input id="pokemonInput" placeholder="Pokemon name" className="border rounded w-1/2"/>
<Button>Pesquisar</Button>
</div>
</div>
<div className="flex justify-center">
<img src="" id="pokemonImage" className="border rounded w-1/2"/>
</div>
</div>
<script type="module" src="./src/script.ts"></script>
</>
)
}
export default App
It should get the string ‘bla bla bla’ and console.log it but I can’t get the property ‘value’, no matter what.
2
Answers
You are trying to get the ‘value’ property on a h1 element, which doesn’t have this type of property. To get the content of the h1 element, you can set in a const h1 = document.getElementById(‘bla’); and then use another constant to put the property ‘.textContent’ as const h1Value = h1?.textContent;
React is not recommended to affect the DOM without using React as much as possible.
You can use
useRef
hook for get value of H1. You can implement the useRef like below.And then, you can get the value like
inputElement.current?.value
But I’d like to recommend you to use states in React.
States are simple to use it.