React-Native Absolute Paths

Swair AQ
3 min readApr 17, 2020

Cause relativity is too complex..

Working on a RN project and making imports? Easy peasy!

Just like that.

But mess happens when you go in hierarchy and you're just like ../../../views lost count of your dots already? This gradually becomes a nightmare and especially when you're calling same name files i.e. index.js and you just have to go and triple check hierarchy.

Wanna know about real nightmare? it happens when you change file structure and boom! loads of errrors like loads of them anddd long tiering work to set them right back. Haven't got to that already? You will one day.

Relative Paths when hierarchy changes.

Anyway absolute paths are really helpful

  • No changes even when hierarchy change.
  • Easier to understand what's coming from where.
  • No long confusing imports and double checks.

So what is absolute path or relative path anyway?

Relative Path We call a file by following the path we are currently on. For example you want to access your images folder from assets folder and you’re in three nested folder yourself.

<Imagesource={require('../../../assets/images/bg.png')}/>

This is the roller coaster your relative path will take you on.

Absolute Path: We call the file from it's parent folder or source folder not from the whole view hierarchy references. Taking the above example not with cool Absolute path you'll just have to write:

<Imagesource={require('images/bg.png')}/>

But yet again the best point is still we don't have to change anything when file location changes.

Yey!

So, what's the magic spell?

It's pretty simple you just have to go to folder and declare a package.json file in there and inside that file just make key-value pair, key should be named as "name" and value can contain name of your folder, in our case it's "images"

{"name": "images"}

and that's it, just call it wherever you like.

Let's do another example here, shall we.

Declare file in component folder
here's content of file.

and now in our navigator's index.js we can import our components like:

import HomeScreen from 'component/HomeScreen'

So reliable… :D

And that's a wrap, if you want me to cover any of your idea, you can drop it on my twitter: https://twitter.com/Swair_AQ

Until next time, Good Bye.

Oh wait, you nearly forgot to clap!

--

--

Swair AQ

Swair Arshad is a React-Native developer with core in iOS development. — Software Enthusiast. Motive to be better developers together.