Home > Enterprise >  How to Manage Lots of Handlers in React
How to Manage Lots of Handlers in React

Time:10-01

I have several components in a hierarchical structure each of which need several event handlers, handed down through multiple layers. This is what I have in App.js:

...
<Files
  plugins={this.state.plugins}
  folders={this.state.folders}
  hover={this.state.hover}
  editing={this.state.editing}
  onClickFolder={this.handleClickFolder}
  onCreateFile={this.handleCreateFile}
  onCreateFolder={this.handleCreateFolder}
  onDeleteFolder={this.handleDeleteFolder}
  onm ouseEnterFolder={this.handleMouseEnterFolder}
  onm ouseLeaveFolder={this.handleMouseLeaveFolder}
  onStartRenameFolder={this.handleStartRenameFolder}
  onRenameFolder={this.handleRenameFolder}
  onClickFile={this.handleClickFile}
  onDeleteFile={this.handleDeleteFile}
  onm ouseEnterFile={this.handleMouseEnterFile}
  onm ouseLeaveFile={this.handleMouseLeaveFile}
  onStartRenameFile={this.handleStartRenameFile}
  onRenameFile={this.handleRenameFile}
  onStopEditing={this.handleStopEditing}
  onRightClick={this.handleRightClick}
/>
...

Then in components/files.jsx:

...
<FolderList
  src={[]}
  hover={props.hover}
  editing={props.editing}
  folders={props.folders}
  onClickFolder={props.onClickFolder}
  onCreateFile={props.onCreateFile}
  onCreateFolder={props.onCreateFolder}
  onDeleteFolder={props.onDeleteFolder}
  onm ouseEnterFolder={props.onMouseEnterFolder}
  onm ouseLeaveFolder={props.onMouseLeaveFolder}
  onStartRenameFolder={props.onStartRenameFolder}
  onRenameFolder={props.onRenameFolder}
  onClickFile={props.onClickFile}
  onDeleteFile={props.onDeleteFile}
  onm ouseEnterFile={props.onMouseEnterFile}
  onm ouseLeaveFile={props.onMouseLeaveFile}
  onStartRenameFile={props.onStartRenameFile}
  onRenameFile={props.onRenameFile}
  onStopEditing={props.onStopEditing}
  onRightClick={props.onRightClick}
/>
...

And so on with two more files. As you can see the code is starting to look quite messy and is against the concept of DRY (don't repeat yourself) in programming, since when I create a new handler I have to update all four files. What I'm asking is if there's a more efficient way to do it.

CodePudding user response:

You have many options. Carefully go through this page. https://www.robinwieruch.de/react-pass-props-to-component

CodePudding user response:

You can try hooks, context or combine your handlers into one object and pass it to your child components, the fields of this object you can validate using PropTypes :)

Also, these examples can helps you

  • Related