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!
>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".