Home > OS >  Not able to update react state with if else condition in child component?
Not able to update react state with if else condition in child component?

Time:12-14

I have a component I want to update parent state from child component clicked. But there is if else condition due to this I'm not able to update state in parent component.

I have two boxes with if else condition & I want to update state in both boxes but its update in only one box. How to solve this?

enter image description here

App.js Code:-

import React, { useState } from "react";
import "./styles.css";
import Halfbox from "./Halfbox";

export default function App(props) {
  const [name, setName] = useState(false);
  if (props.type == "left-section") {
    return (
      <div className="App">
        <b > {name ? <>right update</> : <>right not update</>}</b>
        <Halfbox setName={setName} />
      </div>
    );
  } else if (props.type == "right-section") {
    return (
      <div className="App">
        <b > {name ? <>left update</> : <>left not update</>}</b>
        <p>This is left box</p>
      </div>
    );
  }
}

Halfbox.js Code:-

export default function Halfbox(props) {
  const handleClick = (e) => {
    props.setName(true);
  };

  return (
    <div>
      <h1>Halfbox</h1>
      <button onClick={handleClick}>Click</button>
    </div>
  );
}

Thanks for your efforts!

CodePudding user response:

It seems that there are 2 instance of App, therefore each has its own name state. And the event is only updating the state for its parent App but not the other one.

To have both boxes updated, perhaps a very basic approach could be try moving them down as child components of the same App, so that they can share the name state passed down from it.

Example: (forked live on: codesandbox)

export default function App(props) {
  const [name, setName] = useState(false);
  return (
    <>
      <Section
        type="left-section"
        title="Left Section"
        name={name}
        setName={setName}
      />
      <Section
        type="right-section"
        title="Right Section"
        name={name}
        setName={setName}
      />
    </>
  );
}

export const Section = (props) => {
  if (props.type === "left-section") {
    return (
      <div className="App">
        <b className="state">
          {props.name ? <>right update</> : <>right not update</>}
        </b>
        <Halfbox setName={props.setName} />
      </div>
    );
  } else if (props.type === "right-section") {
    return (
      <div className="App">
        <b className="state">
          {props.name ? <>left update</> : <>left not update</>}
        </b>
        <p>This is left box</p>
      </div>
    );
  }
};
  • Related