How to create a custom Text - react native

Viewed 8555

I completed my project now I want to set my custom font to all Text component.

I think the best way is to create a custom Text component and replace it with default Text of react-native.

now how can I creating a custom Text component with default style?

3 Answers

To achieve that, you need to have a react native component that is configurable via style or other properties once instantiated.

For example you can have your custom react native component CustomText like this:

1. Function component

If you prefer the new way and you'll use it with hooks, use this part:

// CustomText.js    
import React from 'react';
import {
  Text,
  StyleSheet,
} from 'react-native';

export default function CustomText(props) {
  return (
    <Text style={[styles.defaultStyle, props.style]}>
      {props.children}
    </Text>
  );
}

const styles = StyleSheet.create({
  // ... add your default style here
  defaultStyle: {
  },
});

2. Class component

If you prefer the old way with classes use this part:

// CustomText.js    
import React from 'react';
import {
  Text,
  StyleSheet,
} from 'react-native';

export default class CustomText extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Text style={[styles.defaultStyle, this.props.style]}>
        {this.props.children}
      </Text>
    );
  }
}

const styles = StyleSheet.create({
  // ... add your default style here
  defaultStyle: {
  },
});

And then on your main component you import and call that custom component, something like this:

import CustomText from './CustomText';
//... other imports go here.

// in the render method you call your CustomText component.
render(){

//...
  <CustomText style={{ fontWeight: 60, }}>
    This is custom Text
  </CustomText>
}

Note: If you want only to change the style I think @Yanush solution is the best for that case.

I hope this is helpful.

this guide will help you on how to apply custom fonts, I have been using the method in my apps. To create a custom text component

export default Text = (props)=>{
return(
<Text style={[styles.defaultStyles,props.style]}>{props.children}</Text>
)
}

Now in all the files where you have used Text from react native remove import from react native and add

import Text from './path/to/component'

I would suggest using a style instead of a custom component but it's up to you. In my project I have created a file named "commonStyles.js" that looks like this:

export default StyleSheet.create({
    textTitle: {
        fontSize: 20,
        color: '#dddddd',
        fontFamily: 'YourCustomFont',
    },
});

then I'm importing this file wherever needed using:

import stylesCommon from './styles/stylesCommon';

and each text that needs to be changed should look like this:

<Text style={stylesCommon.textTitle}>
This is my title
</Text>
Related