Joseph Richardo
Joseph Richardo

Reputation: 25

Text position in React Native

In react native I want to display some texts at some custom positions like in the following image:

custom location react native

How can I achieve this?

I've been playing with the following example:

import React, { Component } from 'react';
import { Text, StyleSheet } from 'react-native';

export default class TextInANest extends Component {
  constructor(props) {
    super(props);
    this.state = {
      titleText: "Bird's Nest",
      bodyText: 'This is not really a bird nest.'
    };
  }

  render() {
    return (
      <Text style={styles.baseText}>
        <Text style={styles.titleText} onPress={this.onPressTitle}>
          {this.state.titleText}{'\n'}{'\n'}
        </Text>
        <Text numberOfLines={5}>
          {this.state.bodyText}
        </Text>
      </Text>
    );
  }
}

const styles = StyleSheet.create({
  baseText: {
    fontFamily: 'Cochin',
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
  },
});

trying to set titleText position to absolute and adding some top and leftvalues but it doesn't seem to work.

Any ideas?

Upvotes: 0

Views: 8545

Answers (2)

akhtarvahid
akhtarvahid

Reputation: 9769

Improved code with working live demo https://snack.expo.io/@akhtarvahid/demo

export default class TextInANest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      titleText: "Bird's Nest",
      bodyText: 'This is not really a bird nest.'
    };
  }

  render() {
    return (
      <Text style={styles.baseText}>
        <Text style={styles.titleText} onPress={this.onPressTitle}>
          {this.state.titleText}{'\n'}{'\n'}
        </Text>
        <Text numberOfLines={5} style={styles.bodyText}>
          {this.state.bodyText}
        </Text>
      </Text>
    );
  }
}

const styles = StyleSheet.create({
  baseText: {
    fontFamily: 'Cochin',
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold'
  },
  bodyText:{
    position:'absolute',
    left:10,
    top:'50%'
  }
});

Upvotes: 1

robinvrd
robinvrd

Reputation: 1848

From your screenshot, we could say that :

  • Go to Jane's profile takes 1/11 of the screen height, and is vertically centered
  • Bird's Nest takes 5/11 of the screen height
  • This is not... takes 5/11 of the screen height

As in React Native, the main axis is the vertical one (items are positionned below each others by default), you should use justifyContent to vertically centered a Text in a View.

So something like the follow should do the trick.

<View style={{ flex: 1 }}>
    <Text>Go to Jane's profile</Text>
</View>
<View style={{ flex: 5, justifyContent: "center" }}>
    <Text>Bird's Nest</Text>
</View>
<View style={{ flex: 5 }}>
    <Text>This is not...</Text>
</View>

Upvotes: 1

Related Questions