Rohit Verma
Rohit Verma

Reputation: 3785

How to update React state with if else condition in child component?

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?

Working sandbox code

Screenshot:

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 class="state"> {name ? <>right update</> : <>right not update</>}</b>
        <Halfbox setName={setName} />
      </div>
    );
  } else if (props.type == "right-section") {
    return (
      <div className="App">
        <b class="state"> {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>
  );
}

Upvotes: 0

Views: 67

Answers (1)

John Li
John Li

Reputation: 7447

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

Upvotes: 1

Related Questions