简体   繁体   中英

Update state of a functional component from outside of that component(on click of button in another file) in React

I have a component Named Settings which contains a variable(IsActive) with useState defaulted to true. I need to update state of a variable(IsActive) from outside of that component on the click of a button. That button is not a part of this component. How Can I change the state of that variable on the click of a button.

file Settings.tsx

 import React, { useState } from "react";
 import ReactDOM from "react-dom";

 export const reportSettings = () => {
    ReactDOM.render(<Settings />, document.querySelector('.setting-container'));
 };

 const Settings = () => {
    const [isActive, setIsActive] = useState(true);

    return (
        <div>
           <input type="text" disabled={isActive} />
        </div>
    );
};

export default Settings;

I have another file named index.tsx which has a button, on click of it I need to change the state of settings component. How do I do it?

file Index.tsx

  $(".btn-success").on("click", function() {
   //change state of settings component
  });

If you were using only React I would have suggested you to use Redux or React custom hooks. Since JQuery is also being used there is yet another way - Through Custom Event

const event = new CustomEvent("settings", {
  isActive: false
});
$(".btn-success").on("click", function() {
    window.dispatchEvent(event);
});



// Settings.tsx
  const [isActive, setIsActive] = useState(true);

  React.useEffect(() => {
    const toggleFunc = (ev) => {
      setIsActive(ev.isActive)
    };

    window.addEventListener("settings", toggleFunc);

    // Remove listener
    return () => window.removeEventListener("settings", toggleFunc);
  });

You could use CustomEvents . Create a custom event. Fire the event from jquery and an event listener on your react component. Update the state when the event listener is called.

You can lift the isActive to upper component to make it available for the button to change it. So lift the isActive variable to index.tsx and pass it button and also to Settings component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM