Achieving Text Alignment in React Native

I am currently working on styling my project, and I have added a slug description which I hardcoded temporarily to improve its appearance. However, there are two issues that I am trying to address. Firstly, I am unable to align the slug text properly. Secondly, when the text is too lengthy, it wraps around and distorts everything. Ideally, I would want it to be reduced in size and display an ellipsis (...) instead. Is it possible to achieve these changes?

import { StyleSheet, Text, View, FlatList, SafeAreaView, Image } from 'react-native'

export default function App() {
    const present = [{
        id: 1,
        name: 'PresentOne',
        slug: 'PresentOne Slug',
        image: require('../assets/present.jpeg')
    },
    {
        id:2,
        name: 'PresentTwo',
        slug: 'PresentTwo Slug',
        image: require('../assets/present2.jpeg')
    }, 
    {
        id:3,
        name: 'PresentThree',
        slug: 'PresentThree Slug',
        image: require('../assets/present3.jpeg')
    }, 
    {
        id:4,
        name: 'PresentFour',
        slug: 'PresentFour Slug',
        image: require('../assets/present4.jpeg')
    }, 
    {
        id:5,
        name: 'PresentFive',
        slug: 'PresentFive Slug',
        image: require('../assets/present5.jpeg')
    },  
];

const onePresent = ( { item } ) => (
    <View style={styles.item}>
        <View style={styles.avatarContainer}>
            <Image source = {item.image} style={styles.avatarContainer}/>
        </View>
            <Text style={styles.name}> {item.name}</Text>
            <Text style={styles.slug}>{item.slug}</Text>
    </View>
)

const headerComponent = () => {
  return <Text style={styles.listHeadline}>Presents</Text>
}

const itemSeperator = () => {
    return <View style = {styles.seperator}/>
}

return (
        <SafeAreaView >
            <FlatList
            ListHeaderComponentStyle={styles.listHeader}
            ListHeaderComponent={headerComponent}
            data = { present }
            renderItem = { onePresent }
            ItemSeperatorComponent = { itemSeperator }
            ListEmptyComponent = { <Text>Empty</Text>}
            />
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    slug:{
        transform: [{translateX: -100}],
        // alignContent: 'center',
        flexDirection: 'column',
        alignItems: 'center',
    },
    name:{
        transform: [{translateY: -30},{translateX: 10}],
        fontSize: 20,
    },
    listHeadline:{
        color:'#333',
        fontSize: 21,
        fontWeight: 'bold',
    },
    item: {
        flex:1,
        flexDirection:'row',
        alignItems:'center',
        paddingVertical:13,
    },
    avatarContainer:{
        backgroundColor:'#D9D9D9',
        borderRadius:100,
        height:89,
        width:89,
        justifyContent:'center',
        alignItems: 'center',
        margin:10,
    },
    listHeader:{
        height:55,
        alignItems:'center',
        justifyContent: 'center'
    },
    seperator: {
        height: 1,
        width: '100%',
        backgroundColor: '#CCC', 
    }
})

https://i.sstatic.net/lh2hP.png

Answer №1

The textAlign attribute may be what you are looking for. I noticed that you were using the transform property to position the text within your view, but there is a more efficient way to arrange your components without needing to do so (see demo).

import {
  StyleSheet,
  Text,
  View,
  FlatList,
  SafeAreaView,
  Image,
} from 'react-native';

export default function App() {
  const present = [
    {
      id: 1,
      name: 'PresentOne',
      slug: 'PresentOne Slug',
      image: require('./assets/snack-icon.png'),
    },
    {
      id: 2,
      name: 'PresentTwo',
      slug: 'PresentTwo Slug',
      image: require('./assets/snack-icon.png'),
    },
    {
      id: 3,
      name: 'PresentThree',
      slug: 'PresentThree Slug',
      image: require('./assets/snack-icon.png'),
    },
    {
      id: 4,
      name: 'PresentFour',
      slug: 'PresentFour Slug',
      image: require('./assets/snack-icon.png'),
    },
    {
      id: 5,
      name: 'PresentFive',
      slug: 'PresentFive Slug',
      image: require('./assets/snack-icon.png'),
    },
  ];

  const renderPresent = ({ item }) => (
    <View style={styles.item}>
      <View style={styles.avatarContainer}>
        <Image source={item.image} style={styles.avatarContainer} />
      </View>
      <View style={styles.slug}>
        <Text style={styles.name}>{item.name}</Text>
        <Text style={styles.slug}>{item.slug}</Text>
      </View>
    </View>
  );

  const renderHeader = () => {
    return <Text style={styles.listHeadline}>Presents</Text>;
  };

  const renderSeparator = () => {
    return <View style={styles.separator} />;
  };

  return (
    <SafeAreaView>
      <FlatList
        ListHeaderComponentStyle={styles.listHeader}
        ListHeaderComponent={renderHeader}
        data={present}
        renderItem={renderPresent}
        ItemSeparatorComponent={renderSeparator}
        ListEmptyComponent={<Text>Empty</Text>}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  slug: {
    // transform: [{translateX: -100}],
    // alignContent: 'center',
    flexDirection: 'column',
    alignItems: 'center',
  },
  name: {
    // transform: [{translateY: -30},{translateX: 10}],
    fontSize: 20,
  },
  listHeadline: {
    width: '100%',
    color: '#333',
    fontSize: 21,
    fontWeight: 'bold',
  },
  item: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 13,
  },
  avatarContainer: {
    backgroundColor: '#D9D9D9',
    borderRadius: 100,
    height: 89,
    width: 89,
    justifyContent: 'center',
    alignItems: 'center',
    margin: 10,
  },
  listHeader: {
    height: 55,
    alignItems: 'center',
    justifyContent: 'center',
  },
  separator: {
    height: 1,
    width: '100%',
    backgroundColor: '#CCC',
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React - utilizing dynamic properties using string values

I am facing a challenge in my test suite where I need to generate components with dynamic props. The desired components should look like this: <Button primary /> <Button secondary /> However, I am currently stuck at this point: [ &apos ...

Implementing a Timer on an HTML Page with JavaScript

I am looking to add a timer to my HTML page using JavaScript. The timer should get the selected date and time from an input field <input type="date" /> and control it. If the time difference between the current time and the selected time is less than ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...

Cross-Domain Image Uploading

I've been attempting to enable image uploads from one domain to another (CORS). Everything runs smoothly on Localhost, but when I try it on an actual domain, I consistently encounter this message in the Developer Console: Invalid request In my uplo ...

The Vue.JS application encountered an error while making an API request, resulting in an uncaught TypeError: Cannot read properties of undefined related to the 'quote'

<template> <article class="message is-warning"> <div class="message-header"> <span>Code Examples</span> </div> <div class="message-body"> ...

Ways to customize the border color on a Card component using React Material UI

Is there a way to change the border color of a Card component in React Material UI? I attempted using the style property with borderColor: "red" but it did not work. Any suggestions on how to achieve this? ...

Issue with JavaScript HTML Section Changer not functioning properly

I need to implement a button that switches between two pages when pressed. Although the code seems simple, I am struggling to make it work. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Ways to bypass HostListener in Angular 2

In the process of developing a page with animations triggered on scroll, I encountered the challenge of ensuring that the animations only occur when the corresponding element is visible on the viewport. Utilizing Angular2 for this task led me to investigat ...

Setting up a new package through JPSM installation

I utilize jspm in my web application. My goal is to install the npm:angular2 package without needing to set it up in the config.js file. Instead of loading the angular2 module via jspm, I manually added the angular2 library like this: <script src="jspm ...

What is the best way to display a linked page within a <td> element in my specific situation?

I have created an HTML table. Let's say I have a link, such as a link to www.nokia.com. Is it possible for me to display the linked page as content within the table element when "click me" is clicked? If so, how can I achieve this? <a href="#"&g ...

Utilizing Vue CLI's sourcemaps to pinpoint the styling within a Vue component file

Currently, I am working on a Vue CLI project. After setting up the project and making some development changes, my package.json file now includes: package.json "dependencies": { "bootstrap": "^4.3.1", "core-js": "^3.0.1", "preload-it": "^1.2. ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

Offspring of the superior element resting above another element

I'm dealing with a unique situation involving the Z-INDEX property. Check out my HTML setup below. <div class="player"> <div class="player-line"> <div class="player-handle"></div> <!-- /.player-handle --> </d ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

When Vue is used to hide or show elements, MDL styles may be inadvertently removed

When an element is hidden and shown using Vue, some MDL styles may disappear. Take a look at this example on CodePen: https://codepen.io/anon/pen/RBojxP HTML: <!-- MDL --> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=M ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...

Is there a way for me to obtain latitude at the upper boundary of mapbox?

provides latitude and longitude based on mouse position, but I am looking for a way to retrieve the coordinates at the northernmost point of the map relative to its center. Is there a built-in method that allows me to access this information? ...