I want to convert react hooks component to class component but I get error.
HOOKS
import React, { useEffect, useRef } from "react";
const App = () => {
const refValt = useRef(null);
const myfuncValt = () => {
console.log("222222222222222222222");
};
useEffect(() => {
setTimeout(() => {
refValt.current.click();
}, 5000); //miliseconds
}, []);
return (
<div>
<div ref={refValt} onClick={myfuncValt}>Valt</div>
</div>
);
};
export default App;
CLASS
import React from "react";
const myfuncValt = () => {
console.log("222222222222222222222");
};
class App extends React.Component {
constructor(props) {
super(props);
const refValt = React.createRef(null);
}
componentDidMount() {
setTimeout(() => {
this.refValt.current.click();
}, 5000);
}
render() {
return (
<div>
<div ref={this.refValt} onClick={myfuncValt}>
Valt
</div>
</div>
);
}
}
export default App;
I get this error =
I try this.refValt.click(); But It doesn't working.
Actually I suspect the differences between createref vs useref.
CodePudding user response:
This:
const refValt = React.createRef(null);
... needs to be this:
this.refValt = React.createRef(null);