Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom Text - react native

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?

like image 812
S.M_Emamian Avatar asked Jan 29 '26 13:01

S.M_Emamian


1 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.

like image 53
ismnoiet Avatar answered Jan 31 '26 01:01

ismnoiet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!