This is the most frequent problem I come across, in this file was trying to access the innerHTML of the textarea using the same property.
But the error says that the input.innerHTML is null.
You can understand better by code,
import React, { Component, useEffect, useState } from 'react'
import './Body.css';
import axios from "axios";
import './Body.css'
export default function Navbar() {
let noteArray;
let input = document.getElementById('.input_area') ;
const AddNote = () =>{
console.log("here" ,input.innerHTML) ;
}
return (
<>
<div>
<div className="input_info">
<textarea id='input_area' name="" cols="50" rows="5">op</textarea>
<br />
<button onClick={AddNote} className='add'>Add Note</button>
</div>
<br />
<div id='display_info' >
</div>
</div>
</>
)
}
I tried from class, id, and querySelector but none of them is working.
Can anyone suggest me some edits?
>Solution :
To be sure that the elements of the component has been mounted to the DOM you need to execute the selection queries in useEffect hook.
import React, { Component, useEffect, useState } from 'react'
import './Body.css';
import axios from "axios";
import './Body.css'
export default function Navbar() {
let noteArray;
useEffect(() => {
let input = document.getElementById('.input_area');
console.log("here" ,input.innerHTML);
})
const AddNote = () =>{
let input = document.getElementById('.input_area');
console.log("here" ,input.innerHTML);
}
return (
<>
<div>
<div className="input_info">
<textarea id='input_area' name="" cols="50" rows="5">op</textarea>
<br />
<button onClick={AddNote} className='add'>Add Note</button>
</div>
<br />
<div id='display_info' >
</div>
</div>
</>
)
}
Also, I suggest you use useRef instead of DOM select queries.
For example
import React, { Component, useEffect, useState, useRef } from 'react'
import './Body.css';
import axios from "axios";
import './Body.css'
export default function Navbar() {
let noteArray;
const textAreaRef = useRef(null)
useEffect(() => {
console.log(textAreaRef.current.innerHTML)
})
const AddNote = () =>{
console.log(textAreaRef.current.innerHTML)
}
return (
<>
<div>
<div className="input_info">
<textarea ref={textAreaRef} id='input_area' name="" cols="50" rows="5">op</textarea>
<br />
<button onClick={AddNote} className='add'>Add Note</button>
</div>
<br />
<div id='display_info' >
</div>
</div>
</>
)
}