Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create index file full of exports react-native

Tags:

react-native

Is it possible in react native to create an index file from which you can refer to for imports rather than doing '../../folder/component'?

I have tried a few different methods, including the following:

components folder

-> chat
  -> Chat.js
-> dashboard
  -> Dashboard.js
-> home
  -> Home.js
-> index.js

index.js

import Home from './home/Home'
import Dashboard from './dashboard/Dashboard'
import Chat from './chat/Chat'

module.exports = {
    Home,
    Dashboard,
    Chat,
}

Then inside a component, lets say Dashboard, import { Home, Chat } from '../components'

Another method:

index.js

export Home from './home/Home'
export Dashboard from './dashboard/Dashboard'
export Chat from './chat/Chat'

I also tried surrounding the export with curlies, ex export { Home } from './home/Home' because the compiler threw an error otherwise, but it still did not work this way.

I also tried the method inside this users question Requiring Modules in react-native

Is this functionality possible in react-native?

like image 615
wizloc Avatar asked Jun 16 '17 13:06

wizloc


1 Answers

Yes, it is possible. Do the following.

Do named exports from Component files.

from Home.js

export { Home };

from Chat.js

export { Chat };

from Dashboard.js

export { Dashboard };

where Home, Chat and Dashboard are the components names in the respective files.

Now in your index.js Do following:

export * from './home/Home';
export * from './chat/Chat';
export * from './dashboard/Dashboard';

use them in other files like this:

import { Home, Chat, Dashboard } from '../components'

Update 1

If you are using redux and want to export the component which is connected to the store, then use the following:

Store the connected component in a const variable like this:

const HomeComponent = connect(mapStateToProps, mapDispatchToProps)(Home)

then export it like this:

export { HomeComponent }
like image 158
Ankit Aggarwal Avatar answered Oct 01 '22 20:10

Ankit Aggarwal