React Native: Image not aligning vertically center in text within nested elements

Issue Description

I am facing a challenge in nesting multiple images within a paragraph. If it were just a single line of text, I could have easily used a <View> with flexDirection: 'row'. Since that approach doesn't fit the requirement, I decided to encapsulate all the texts and images within <Text>.

Reference Image

Although my current method allows the images to nest, they are not aligned centrally with the text. I have made several attempts to fix this alignment issue which can be seen in the styles.fix section.

In the highlighted segments, the envelope image aligns with the baseline of the text instead of being vertically centered within each highlighted red box.

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

Snippet

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

import Img from './img.png';

export default () => {
  return (
    <SafeAreaView style={styles.rootContainer}>
      <View style={styles.container}>
        <Text>
          <Text>This paragraph contains an icon here </Text>
          <Image style={[styles.img, styles.fix]} source={Img} />
          <Text> on the next line as well </Text>
          <Image style={[styles.img, styles.fix]} source={Img} />
          <Text> and also here </Text>
          <Image style={[styles.img, styles.fix]} source={Img} />
          <Text> however, the icons are not perfectly centered with the text.</Text>
        </Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  rootContainer: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    margin: 20,
    padding: 20,
    borderWidth: 1,
    borderRadius: 5,
  },
  img: {
    width: 23,
    height: 15,
  },
  fix: {
    /**
     * `attempted using relative positioning to lower the position but it was unsuccessful`
     * top: 10,
     * position: 'relative',
     *
     * `margin adjustment didn't work either as it distorted the icon proportions`
     * marginTop: 10,
     *
     * tried wrapping Image in a View with
     * marginTop or relative positioning but the
     * outcome resembled the previous two methods
     */
  },
});

Answer №1

Have you looked into this? Tips for vertically aligning text and icons in React

I suggest trying the alignItems: "center" property within a View component to achieve vertical alignment, instead of using align-items with flex.

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

Issue with React rendering numbers without displaying div

In my user interface, I am attempting to display each box with a 1-second delay (Box1 after 1 second, Box2 after another 1 second, and so on). https://i.sstatic.net/FdTkY.png However, instead of the desired result, I am seeing something different: https ...

Refresh customer information on database modification

Currently working on my inaugural SaaS B2C application with the technology stack of ReactJS + Relay + GraphQL + MongoDb. To provide context, the application will incorporate various objects, such as: User Customer StockItem StockLevel PriceList Sales Ret ...

When the previous textbox is filled, the cursor will automatically move to the button

Utilizing an RFID reader where students tap their ID to display basic info, a hidden button on the form opens a modal with various purposes for selection. The challenge is shifting focus of cursor to the button and automatically clicking it when the last ...

Using Vuejs: incorporating imported plugin mixins locally

Can a mixin from a VueJS plugin be used in just one component? I made a plugin and noticed that once I import it, I can use the mixin's functions in all my components. Is there a method to restrict it to just one component, or do plugins inherently ...

What is the best way to display the key within an object in a mui-datatable?

I attempted to define it in the following manner: { name: "colorList", label: "Color", options: { filter: true, sort: true, customBodyRender: (value, tableMeta, updateValue) => { ...

Is it possible to utilize create-react-app without an internet connection?

Is there a method to utilize create-react-app offline instead of constantly downloading files from the internet? It feels like such a waste of bandwidth and time, especially considering that internet speeds are slow and costly in my area. ...

Should CSS variables be defined within the render method of a React component?

Yesterday, I mistakenly created and deleted a post. Now, I am facing an issue with creating a component that requires specific styling. The problem arises when the componentDidMount() method causes flickering during the rendering process, as it takes some ...

Is there a way to associate a click event with an angular2 template interpolation?

Can a click event be bound to an interpolation? Whenever I try to run the code below, I encounter the following ERROR Error: Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at col ...

Having difficulties setting up React JS on my Windows X64 operating system

Looking to set up React JS with the npx command...I attempted to install React JS by running these commands...but unfortunately, it doesn't seem to be successfully installing React after reaching the last two lines shown in the image. ...

Numerous obj elements simultaneously loaded within a single viewport

My goal is to incorporate multiple obj models into separate scenes, following the concept from webgl_multiple_elements.html. I have successfully loaded a single obj file and now want to add it to each individual scene. Although the obj file loads without ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

Issue with using useState inside alert: unexpected empty array

I am facing an issue with the 'exercises' useState in my code. The useEffect function correctly prints the 'exercises' after every change, but when I press the 'Finish' button, the 'exercises' suddenly become empty. ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

What could be causing the "fetch is not defined" error to appear on my screen?

I attempted to create a unique email receipt template using SendGrid with commercejs webhooks, following the steps outlined in this tutorial. The corresponding code can be found on this GitHub repository, which has been deployed to this test Netlify site. ...

What is the alternative way to achieve this functionality in Javascript without relying on jQuery?

I am encountering some dependencies issues with jQuery that are preventing me from using it. However, I still need to find a way to make this work without relying on jQuery libraries. Do you have any suggestions on how to achieve this? $(document).ready ...

Make the current tab the active tab with the help of AngularJS

I have a set of five tabs that are functioning correctly. However, when I refresh the page, the active tab reverts back to its default state instead of staying in its current active state. Can anyone help me identify where I may be making a mistake? Here ...

Looking to distinguish selected options in a multiple select in AngularJS by making them bold?

When working with Angular, I have a multiple select drop down with options such as Select fruits, Apple, Orange, Banana. How can I make the selected options, like Banana and Apple, appear in bold and change background colors? ...

I am having trouble running my JavaScript code outside of JSFiddle

It's strange how my code functions perfectly in JSFiddle, but when I attempt to use it outside of JSFiddle, it fails to work. Can anyone provide a solution or insight into what might be causing this issue? Feel free to check out the JSFiddle code here ...

HTML Brickwork Picture Arrangement

I recently integrated this code into a WordPress theme and encountered an issue where the new images are displaying vertically instead of horizontally. I am seeking assistance in aligning the new images to appear on the green line instead of the red line a ...

Finding the date of a month prior based on a fixed initial date - here's how!

I have a specific requirement to display a subscription date range on a webpage in the following format: 31 May 2023 — 30 June 2023 When a user subscribes, the backend sends a fixed subscription start date that remains constant. For example, if a user ...