Code reuse in React

Asked

Viewed 345 times

0

I have a code that repeats on every page.

How can I solve this problem by reusing the script.

export default class App extends Component<{}> {
   onMenuItemSelected = item =>{
      if(item == "inicial")
      {
         Actions.inicial();
      }
      else if(item == "agendamento")
      {
         Actions.agendamento();
      }
   }

   render() {
      const menu = <Menu onItemSelected={this.onMenuItemSelected} />;
      return (
         ...
      );
   }
}

In case I would like to reuse the code of onMenuItemSelected.

  • There are several ways to do this, if you give more details about how this application is, it will be easier to find the best solution.

  • I have a menu "hamburguer" which is a separate View, and on each page I am repeating this code which is called load other "pages" from the app, I tried to put in the same code from the menu, but I would need to create a file where I can put the global codes.

  • You can make a parent component as a <Layout/> for example and maintain everything that is global in that component. Inside it you maintain a placeholder children or more than one placeholder if applicable, for you to go feeding that <Layout/> with the content of the page.

1 answer

1

One way is to create your own component for the Menu:

class MeuMenu extends Component {
   onMenuItemSelected = item =>{
      if(item == "inicial")
      {
         Actions.inicial();
      }
      else if(item == "agendamento")
      {
         Actions.agendamento();
      }
   }

   render() {
      return <Menu onItemSelected={this.onMenuItemSelected} />;
   }
}

And use it anywhere:

export default class App extends Component<{}> {
   render() {
      const menu = <MeuMenu />;
      return (
         ...
      );
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.