0

This is a general ES6 question, but I've encountered it in the context of React Native. The basic problem is that I want to override some components that I usually import from the 'react-native' module with my own components. My method for doing this looks like the following:


Instead of requiring components with import { Text, View, etc } from 'react-native'

require them like this: import { Text, View, etc } from './ui_components'

where ui_components.js looks something like:

export * from 'react-native'


The issue is, how do I add my own components to this export? Ideally I'd be able to add them in ui_components.js by doing something like this:

import * as RN from 'react-native'
RN.Text = myTextComponent
RN.View = myViewComponent
export * from RN

But this doesn't quite work. Any ideas?

2

1 Answer 1

1

You need to import React Native's component and reexport it, with or without extensions from your side - it's up to you.

But remember - don't ever override React's internals (or any other's internals). Components are composable, yay!

For example, here, I am creating my custom Text component cause I want all texts in my app to be red by default. Also I want it to be configurable if I need different color for title/subtitle/whatever...

import React from 'react';
import { Text as NativeText } from 'react-native';

export default function Text({ style, ...props}) {
    return <NativeText style={[ { color: 'red' }, style]} {...props} />
}

Got an idea?

Good, now to folder structure...

ui_components
| - index.js
| - Text.js

// Text.js
// See example above...

// index.js
export { default as Text } from './Text';

// In your app
import { Text } from './ui_components';
Sign up to request clarification or add additional context in comments.

1 Comment

This helps, thank you. I was hoping to make it so that I could import all my components from the same place, whether they were custom or not. But keeping them separate is probably better for code clarity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.