Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function inside stateless component

before someone as this duplicate to this question Can you write nested functions in JavaScript?

I am wondering if we can do something like this?

const toolbar = (props) => {
let sidedrawer = false;

  showSideDrawer = () => {
    sidedrawer = !sidedrawer
  }

  return (
    <header className={Classes.Toolbar} purchasingHandlerClose={this.showSideDrawer}>
//Something here
    </header>
  )
}
export default toolbar;

More precisely, something like this in functional component

 showSideDrawer = () => {
        sidedrawer = !sidedrawer
      }

and then calling it like this

  <header className={Classes.Toolbar} purchasingHandlerClose={this.showSideDrawer}>

Now, I know we can do this stateful component or class but then again in JS, Class is just syntactical sugar (still trying to figure out the meaning of the phrase), so how can we implement something like this in stateless or functional component?

like image 578
iRohitBhatia Avatar asked Jun 13 '18 07:06

iRohitBhatia


1 Answers

You can write a function within a stateless functional component, however function component don't have a this variable and in order to call the function you would simply write

const toolbar = (props) => {
  let sidedrawer = false;

  const showSideDrawer = () => {
    sidedrawer = !sidedrawer
  }

  return (
    <header className={Classes.Toolbar} purchasingHandlerClose={showSideDrawer}>
//Something here
    </header>
  )
}
export default toolbar;

However one pitfall of the above is that everytime the toolbar component is rendered sidedrawer is initiased to false and hence the showSideDrawer doesn't work as expected. You can however move the sidedrawer variable outside of functional scope and it will work

let sidedrawer = false;
const toolbar = (props) => {

  const showSideDrawer = () => {
    sidedrawer = !sidedrawer
  }

  return (
    <header className={Classes.Toolbar} purchasingHandlerClose={showSideDrawer}>
//Something here
    </header>
  )
}
export default toolbar;

However in this case too, the showSideDrawer function is also created everytime toolbar is render which isn't the right way to do and hence if you want to have such a functionality its always advisable to write a class component instead of a functional component because functional components are supposed to be pure..

like image 54
Shubham Khatri Avatar answered Oct 08 '22 02:10

Shubham Khatri