Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native fit Text Component

I'm trying to fit my text inside available area and my constraints are something like this:

  • Text should not overflow,
  • Text must scales up inside all available view,
  • Words should not broken into characters and goes to next line sentences can be,
  • When I'm using flex inside parent view text should not expand view more than screen width horizontally.

Here is my code snippet:

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Font } from "expo";
import Lorem from "./src/helpers/lorem-ipsum-gen";

export default class App extends React.Component {
  constructor() {
    super()
    this.state = {
      fontLoaded: false,
    };
  }
  //theboldfont.ttf
  async componentWillMount() {
    await Font.loadAsync({
      "akzidenz-grotesk-bq-bold": require("./assets/fonts/AkzidenzGrotesk_BQ_Bold.otf"),
    });
    this.setState({ fontLoaded: true });
  }

  render() {
    let loremText = new Lorem().generate(20)

    return (
      <View style={styles.container}>
        <View>
          <View style={{ flex: 0.37 }} > </View>
          <View style={{ flex: 0.25, backgroundColor: "red" }} >
            <View >
              {
                this.state.fontLoaded ? (<Text
                  style={{ fontFamily: "akzidenz-grotesk-bq-bold", fontSize: 50 }}
                  adjustsFontSizeToFit={true}
                >
                  {loremText}
                </Text>) : null
              }

            </View>
          </View>
          <View style={{ flex: 0.38 }} >
            <Text>
              {loremText}
            </Text>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

And result of it:

sample screenshot

What I've tried to achieve my goal:

  • I thought it's related with custom font & changed to default font(Not worked)
  • In some github issues people wrote adjustsFontSizeToFit={true} inside text style prop (Not worked)
  • I tried allowFontScaling (Not worked)
  • Removed fontsize (Not worked)
  • Removed flex and set static width and height to view (Not worked)
  • Combinations of all steps above (Not worked)
like image 994
Batu G. Avatar asked Sep 03 '25 01:09

Batu G.


1 Answers

So after trying new things on text component I've found that adjustsFontSizeToFit={true} is not working without specifying numberOfLines={number} however it is dividing my words into characters sometimes at the end of the line. And from the docs probably it's not available in android. So I still need a better way to find a solution to my problem

like image 168
Batu G. Avatar answered Sep 04 '25 14:09

Batu G.