Home > Enterprise >  Force react component to re-render after state change
Force react component to re-render after state change

Time:12-28

I have below JSX, which is a popover inside Box. isActive is a prop taken by Popover which keeps the Popover open. Now on click event i am trying to update the value of isActive to keep it open but it's not happening. How to correct it?

const [open, setOpen] = React.useState(false);
<Box variant="light">
  <Popover
    id="myPopover"
    isActive={open}
    items={[
      {
        children: <Type weight="semibold">Popover Item</Type>
      },
      {
        children: <Type weight="semibold">Popover Item</Type>
      },
      {
        children: <Type weight="semibold">Popover Item</Type>,
        disabled: true
      },
      {
        children: <Type weight="semibold">Click Me</Type>,
        onClick: event => {
          console.log('Clicked', event);
          setOpen(true);
          
        }
      }
    ]}
    
  >
    <div>My Popover</div>
  </Popover>
</Box>;

CodePudding user response:

onClick function should switch the open state from true to false and vice versa. fix your onclick function to be as follow

setOpen(!open);

CodePudding user response:

import React, { useState, useCallback } from 'react';
import { render } from 'react-dom';
import Button from './button';

const App = () => {
const [open, setOpen] = useState(false);

const onClick = useCallback((e) => {
setOpen((prev) => !prev);
}, []);
 return (
  <div>
  {open && <div>show value of open: {open ? 'true' : 'false'} 
  </div>}
  <br/>
  <Button callbackClick={onClick} />
  </div>
  );};

CodePudding user response:

Hi isActive is always false in your code. You should set isActive={open}

Try this esxample

import React, { useState, useCallback } from 'react';

const Example = () => {
  const [open, setOpen] = useState(false);

  const togglePopover = useCallback(() => {
    setOpen=((prev) => !prev)
  }, []);
  
  return (
    <Box variant="light">
      <Popover
        id="myPopover"
        isActive={open}
        items={[
          {
            children: <Type weight="semibold">Popover Item</Type>
          },
          {
            children: <Type weight="semibold">Popover Item</Type>
          },
          {
            children: <Type weight="semibold">Popover Item</Type>,
            disabled: true
          },
          {
            children: <Type weight="semibold">Click Me</Type>,
            onClick: togglePopover
          }
        ]}

      >
        <div>My Popover</div>
      </Popover>
    </Box>;
  );
}

  • Related