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

Why does it say that my variable is not defined?

Here is my react component…
I can’t figure out why nyVariable says that it is not defined…

import React from "react";
import { useEffect } from "react";

const Component = () => {

  useEffect(() => {
    const myVariable = "Jim"
  }, []);

  return(<div>{myVariable}</div>) 
};

export default Component;

Thanks!

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

>Solution :

A variable created inside a useEffect can not be accessed from outside the useEffect. I would recommend looking into how a useEffect and useState work.

Try something like this:

import React from "react";
import { useEffect, useState } from "react";

const Component = () => {
  const [state, setState] = useState("");
  useEffect(() => {
    setState("Jim");
  }, []);

  return(<div>{state}</div>) 
};

export default Component;

This will create a state variable that contains an empty string. Then upon the components first render, will set the state to "Jim".

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