1

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.

1 Answer 1

1

It is possible but you will get circular modules warning, and if you will run jest tests it will throw exception, so if you want to do this better pass the function updateLightsState as a callback parameter - then no problems

function turnOnGreenLight(callback) {
  setLightsVar[1] = "active";
  callback();
}

turnOnGreenLight(updateLightsState)
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry but I fail to understand how to pass the function updateLightsState as a callback parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.