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?
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With