Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Convert Hooks To Class But Get Error

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 =

enter image description here

I try this.refValt.click(); But It doesn’t working.

Actually I suspect the differences between createref vs useref.

>Solution :

This:

const refValt = React.createRef(null);

… needs to be this:

this.refValt = React.createRef(null);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading