Home > Back-end >  Passing React State
Passing React State

Time:07-22

I have a modal that I want to appear on a button click. This works fine, however, in order for it to be positioned correctly, I need to move the modal component to be rendered in a parent component. I'm unsure how to do this as I'm not sure how I would pass the state down to the component where the button click is created. I'm also unsure of whether this is about passing a state or using a button onClick outside the component the state is defined in.

My code works and does what I want, but, I need <DeleteWarehouseModal show={show} /> to be in the parent component below. How can I do this?

The parent component where I want to render my modal:

function WarehouseComponent(props) {
  return (
    <section>
      <div>
          <WarehouseListItems warehouseData={props.warehouseData} />
          //Modal component should go here
      </div>
    </section>
  );
}

The component (WarehouseListItems) where the modal is currently being rendered:

function WarehouseListItem(props) {
  const [show, setShow] = useState(false);

  return (
     <>
//some code necessary to the project, but, irrelevant to this issue

        <Link>
          <div onClick={() => setShow(true)}></div>
        </Link>
      <DeleteWarehouseModal show={show} />
     </>
  );
}

The modal:

const DeleteWarehouseModal = (props) => {
  if (!props.show) {
    return null;
  }
  return (
    //some elements here
  );
};

CodePudding user response:

Yes, you can move the state and it's handler in WarehouseComponent component and pass the handler down to child component, which can change the state in parent component.

WarehouseComponent :-

function WarehouseComponent(props) {
  const [show, setShow] = useState(false);

  const toggleShow = () => {
    setShow(state => !state);
  }
  return (
    <section>
      <div>
          <WarehouseListItems 
            warehouseData={props.warehouseData}
            toggleShow={toggleShow}
          />
          <DeleteWarehouseModal show={show} />
      </div>
    </section>
  );
}

WarehouseListItems : -

function WarehouseListItem(props) {
  const {toggleShow} = props;

  return (
     <>
//some code necessary to the project, but, irrelevant to this issue

        <Link>
          <div onClick={() => toggleShow()}></div>
        </Link>
      
     </>
  );
}

CodePudding user response:

I'm not sure if I'm getting the question but I think you need to create a Portal for the proper render of the Modal

enter link description here

  • Related