Search code examples
javascriptreactjsreact-state-managementreact-functional-component

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
  });

Solution

  • 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.