I want to call a function from a React component. This function will call another function in the component from which it was called.
My component:
import React, { useState } from "react";
// import turnOnGreenLight from "./green.js"; // <-- I want to import this
export const initialLightValues = ["unactive", "unactive"];
export let setLightsVar = initialLightValues;
function App() {
const [lights, setLights] = useState(initialLightValues);
function turnOnRedLight() {
setLightsVar[0] = "active";
updateLightsState();
turnOnGreenLight();
}
// I want to move this function "turnOnGreenLight" in the file green.js
function turnOnGreenLight() {
setLightsVar[1] = "active";
updateLightsState();
}
function updateLightsState() {
setLightsVar = setLightsVar.slice();
setLights(setLightsVar);
}
return (
<div className="App">
<button onClick={() => turnOnRedLight()}>Turn on the lights</button>
<br />
<div className={"red-light " + lights[0]}>Red</div>
<div className={"green-light " + lights[1]}>Green</div>
</div>
)
}
export default App
The function in the file green.js would look like this:
import { setLightsVar, updateLightsState } from "./App";
function turnOnGreenLight() {
setLightsVar[1] = "active";
updateLightsState();
}
export default turnOnGreenLight;
I'm not sure if what I'm trying to do is possible.