How to render another child component in react due to another child component

Viewed 273

A component has 2 child components, on changing the switch value in one of the child component, it should re-render the other child component. How to achieve this? Please explain with a code snippet.

1 Answers

React components render/rerender for 1 of 3 reasons:

  1. The component enqueues a state update.
  2. Any of the passed props change value.
  3. The parent component rerenders.

Causing case 3 is the simplest way to achieve what you ask. The parent component of both children just needs some declared state that child 1 can call a callback prop when it updates its local state.

Example:

const Child1 = ({ onChange }) => {
  const [value, setValue] = React.useState();

  React.useEffect(() => {
    onChange(value);
  }, [onChange, value]);

  return (
    <React.Fragment>
      <h1>Child 1</h1>
      <label>
        Value
        <input
          type="checkbox"
          value={value}
          onChange={(e) => setValue(e.target.checked)}
        />
      </label>
    </React.Fragment>
  );
};

const Child2 = () => {
  React.useEffect(() => {
    console.log("Child 2 render " + new Date());
  });

  return <h1>Child 2</h1>;
};

function App() {
  const [, rerender] = React.useState();

  return (
    <div className="App">
      <Child1 onChange={rerender} />
      <Child2 />
    </div>
  );
}

const rootElement = document.getElementById("root");
const root = ReactDOM.createRoot(rootElement);

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root" />

Note that the key here is to simply get the parent component to rerender. There are other ways to trigger sibling components to rerender via a common ancestor component.

Related