2

I have a useEffect hook which contains an if-else block and 'B1.X.Change' JS function inside an else. Now I am unable to bind 'B1.X.Change' to an element 'changeM' inside function component 'func1'. Any help on how this can be achieved is greatly appreciated.

My code looks like below.

useEffect(() => {
  if (var1 === "") {
    let id = "newvar1";
    if (id === "") {
      if (condition) {
        setP(true);
      } else {
        setP(false);
      }
    } else {
      setvar1(id);
      setP(true);
    }
  } else {
    if (var2 === "xxx" && var3 == null) {
      api
        .getC(var1)
        .then((details) => {
          setvar3(details);
        })
        .catch((reason) => {
          console.log(reason);
        });
    }
    if (condition) {
      //some js script
      B1.X.Change("#changeM", {
        // <do something>
      });
      //some js script
      B1.X.Change("#changeN", {
        // <do something>
      });
      setC(true);
    }
  }
}, [var2, var3]);

function func1() {
  return (
    <Col className="col-4 mt-2 mr-4">
      <Link to="/co" id="changeM">
        {"changeM"}
      </Link>
      <Link to="/co" id="changeN">
        {"changeN"}
      </Link>
    </Col>
  );
}

1 Answer 1

-1

Do you mean to use the function prototype method bind?

If so, this is answered here

How to bind parameters in React hooks' setState() function?

Side note, It's not clear that changeM is an element from your code sample.

Why are you trying to bind B1.X.Change to changeM?

If you are trying to run some code when you click on changeM and changeN, you use event listeners. In React, you can use the onClick property. In the onClick property, you add a function that will be called when the user clicks on that element.

function func1() {
  const someFunc = (kind) => {
    // your logic here. The argument allows you to tell if changeM or changeN was clicked.
  }
  return (
    <Col className="col-4 mt-2 mr-4">
      <Link to="/co" id="changeM" onClick={() => someFunc("changeM")}>
        {"changeM"}
      </Link>
      <Link to="/co" id="changeN" onClick={() => someFunc("changeN")}>
        {"changeN"}
      </Link>
    </Col>
   )
}
Sign up to request clarification or add additional context in comments.

2 Comments

B1.X.Change contains a JavaScript for a widget which should open upon clicking on changeM and changeN
I have edited my answer to show how can accomplish what you need to by using React's onClick handler, inside of bind, which is not possible in React's function components.

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.