'How to pass props from functional component to class component

I'm quite new to functional components and I've been on this for hours. I simply want to pass a prop from a parent functional component to a class child component so that I will use the updated prop (which will be a boolean) to change the display of an element. That's all.

In this scenario, I want to switch the sidenav from opened to closed based on the prop.

Here is the parent component (functional):

   let opened = false;

   function openSidenav(){
       opened = !opened;
   }
   const [sidebarOpened, setOpened ] = useState(opened);

   return (
       <Sidebar sidebarOpened={opened} />
   )

and the child component (class):

   componentDidUpdate(prevProps) {
      if(this.props.sidebarOpened !== prevProps){
         this.setState({ sidebar: true});
      }
   }

It's just not working, the child component isn't receiving changes, I guess I didn't pass the prop rightly. I know the code just needs correction but I don't know where I'm not getting it.

Thank you.



Solution 1:[1]

In parent,

  const [sidebarOpened, setOpened ] = useState(false);

  function openSidenav(){
    setOpened(!sidebarOpened);
  }

  return (
    <Sidebar sidebarOpened={sidebarOpened} />
  )

And in child component class directly use this.props.sidebarOpened instead of copying over the prop to state. If you intend to edit the value of sidebarOpened in the child component, pass setOpened to the child component as a prop and use that to edit the value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1