SpadeX
December 9, 2022, 5:25am
1
I have react code added with plain html when i am searching elements but not getting the hidden type input type element Please any on know why this happens ?
<input type="hidden" id="shop-domain" value="{{shop.domain}}" />
when i am searching in react code this html element not getting and throw an errror.
shop_domain = document.getElementById(‘shop-domain’).value();
following error throws
Uncaught TypeError: Cannot read properties of null (reading 'value')
at <anonymous>:1:39
(anonymous) @ VM395:1
hello @SpadeX
This happens because there is a Lifecycle of React-Component
if you try to access elements in a JSX before render method is called by react, That element will be null
and since you are just accessing the .value
value is a property not a function
without checking whether it exits or not.
you will encounter an ERROR:
Cannot read properties of null
Solution
in functional component put your code inside useEffect hook
useEffect(() => {
console.log(document.querySelector("#shop-domain").value);
}, []);
In class component you can write it on componentDidMount method
class App extends React.Component {
constructor(props) {
super(props);
this.state = { shop: 'lightgreen' };
}
componentDidMount() {
const shop_domain = document.getElementById(‘shop-domain’).value;
console.log(shop_domain)
}
render() {
return (<input type="hidden" id="shop-domain" value={this.state.shop} />)
}
}
system
Closed
June 9, 2023, 6:27pm
3
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.