DRY React Navigation Screens

Justin Rohweller
1 min readSep 23, 2022

--

React Navigation is excellent.
But a lot of the time you end up writing boilerplate to add a screen.

It also (in my opinion) takes too much control. It takes the responsibility of the screenName away from the screen.

At the end of this, adding a new screen will be as easy as adding this to the bottom of said screen file:
ScreenName.shouldBeInStack = true;
ScreenName.title = “ScreenName”;

Step 1: create navigators programmatically from configuration:

Step 2: Write your configuration for how navigators will be nested.

Step 3: Export your screen files in an index.ts file.
src/screens/index.ts
For example:

Step 4: Add Two lines to the bottom of your screen file and you’re done!
(add two lines at the bottom of the file). (lines 5 & 6 below)

And then you’re done! Homescreen will now be in the stack, and can be navigated with navigation.navigate(“Home”);
Bonus: You even can make a script like below to make generating screens even quicker.

I thought I’d share this article to see if anybody else has tried this, and possibly had ideas on improving it. I know the solution isn’t perfect, but I thought it was cool.
Let me know in the comments.

Almost instantly after writing this, Evan Bacon came out with this:

I’d recommend trying that as well.

--

--

Justin Rohweller
Justin Rohweller

Written by Justin Rohweller

I'm a freelance React Native developer that rarely writes articles. I enjoy videogames, soccer, and all the things.

Responses (1)