Tips for positioning 2 React Native elements: have one centered and the other aligned to the beginning

Consider the following React Native styles:

var styles = StyleSheet.create({
  parentView:{
    width: 400,
    height:150
  },
  containerView:{
    flex:1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor:'black'
  },
  child1:{
    backgroundColor: 'red',
    alignSelf: 'flex-start'
  },
  child2: {
    backgroundColor: 'yellow'
  }
}

Now, let's look at this render function:

render: function(){
  return(
      <View style={styles.parentView}>
        <View style={styles.containerView}>
          <Text style={styles.child1}>Child1</Text>
          <Text style={styles.child2}>Child2</Text>
        </View>
      </View>
    );  
}

The code currently generates this image: https://i.sstatic.net/EpW1M.png

However, the desired output is shown in this image: https://i.sstatic.net/SKVU2.jpg

In order to achieve this layout, it is crucial that child2 is perfectly centered within containerView, without being offset due to the space taken by child1.

How can we attain this in a responsive way in React Native?

p.s.: Remember that this will be displayed on various screen resolutions and aspect ratios, so a solution that works universally across different devices is needed.

Answer №1

I found a solution that works well for me, though there may be better ways to accomplish this task.

render() {
    return(
      <View style={styles.parentView}>
      <View style={styles.containerView}>
        <View style={styles.rowContainer}>
          <View style={styles.rowItem}>
            <Text style={styles.child1}>Child1</Text>
          </View>
         <View style={styles.rowItem}>
            <Text style={styles.child2}>Child2</Text>
         </View>
        </View>
      </View>
    </View>
  );

const styles = StyleSheet.create({
  parentView:{
    width: 400,
    height:150
  },
  containerView:{
    flex:1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor:'black'
  },
  rowContainer: {
    flex: 1,
    flexDirection: 'column',
  },
  rowItem:{
    flex: 1
  },
  child1:{
    backgroundColor: 'red',
    position: 'absolute',
  },
  child2: {
    alignSelf: 'center',
    backgroundColor: 'yellow'
  }
});

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

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

Troubleshooting a CORS problem on HEROKU post deployment

Currently, my Node.js server interacts perfectly with my React app on a local environment. However, upon deploying the server to Heroku and updating the URL in my React app, I encountered a CORS preflight request error. Initially, I suspected issues with e ...

Guide to making a sidebar navigation menu on the left using Bootstrap

How can I create a left navbar using Bootstrap? I managed to do it. <nav class="btn-group-vertical float-left navbar"> <button routerLink="product/home" routerLinkActive="is-active" class="btn btn-outline-dark">Home</button> ...

What is the best way to apply a unique style (such as adding a bottom border) to all list items

Currently, I am utilizing React Material components with a List that is internally represented as ul li elements. My goal is to apply a style to all li elements by adding a bottom border. One approach is to include the className={classes.sideBar__listItem_ ...

Managing environment variables in a production server with Webpack post continuous integration can be done in a couple of ways

I am currently working on deploying a ReactJs application in production using Webpack as my build tool. To set environment variables, we are utilizing the DefinePlugin feature. new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( ...

How to target the attribute value of an image element that has a specific parent class using jQuery

I'm working with a list that looks like this: <ul> <li><div class="thumb"><img src="image-1.jpg"></div></li> <li><div class="thumb"><img src="image-2.jpg"></div></li> <l ...

Conditional formatting for form field styles

Is there a way in Angular to conditionally render a material style? For instance, I am looking to apply the following style only to my Password form field text, and only when both input boxes have content: .mat-form-field-appearance-outline .mat-form-fiel ...

Stop the body from scrolling when dialog is open on a mobile screen

I am encountering an issue on a mobile screen where I am displaying a dialog that is longer than the screen size, causing it to scroll. The problem arises when scrolling past the bottom of the dialog (I am utilizing Bootstrap 3) as instead of stopping, it ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

Page Content Fails to Load Without Reloading

I am currently working on a simple project using React with TypeScript, and I have run into an issue where the page content does not refresh as expected without having to reload the page. I am unsure of the underlying cause of this behavior. I have include ...

Choosing elements for react select within a modal using SeleniumIn this guide, we will discuss

In my current project, I am using ReactJS and Selenium WebDriver with Java. The task at hand involves the following steps: Click on a button (completed) This action triggers a modal containing a react select component The goal is to select an elemen ...

Formik's setFieldValue function exhibits a delay in updating the state, resulting in a one-render lag

I've set up a formik form with initial values of { email: "", password: "", method: "manual" }. In my GoogleLogin component from react-oauth/google, I want to update the value of method to 'google' inside the on ...

"Utilizing the flex box feature in IE 10 for efficient text trunc

.container { background: tomato; width: 100px; display: flex; } .text-left { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .text-right { } <div class=container> <div class="text-left"> title title title ...

I am looking to implement a feature in my quiz application where a green tick mark appears next to the question number for the correct answer and a red cross mark for the wrong answer

My HTML code here retrieves questions from a database and displays them based on the question number. <h4>{{indexOfelement+1}}</h4>&nbsp;&nbsp; In my CSS, I need to style the questions as follows: How can I achieve this? Each question ...

Allowing breaks with the :nth-child() selector

There must be a straightforward explanation for this perplexing issue. However, in my view, it ought to function as intended. We are currently utilizing the Bootstrap 3 CSS framework. The following code is present on a specific page: <div class="promo ...

Using axios to fetch data and display it in a React table

I have been attempting to store the data retrieved from an axios.get request into a variable and then pass it through a Table component in order to display the data on the table. import { useMemo, useState } from "react"; import fellar from " ...

Steps for incorporating a quantity option in ReactJS for PayPal transactions

I am having trouble adding the quantity of an order. The code I have doesn't seem to be working properly. It works fine without specifying the quantity, but then it defaults to 1. Additionally, I'm unsure how to add a second product as it's ...

Typing into the styled M-UI TextFields feels like a never-ending task when I use onChange to gather input field data in a React project

Having an issue where entering text into textfields is incredibly slow, taking around 2 seconds for each character to appear in the console. I attempted using React.memo and useCallback without success :/ Below is my code snippet: const [userData, setUserD ...

Using Bootstrap: adjusting the height of input-group and select elements

How come the select element within an input-group doesn't render similarly to the input element? I would like the height of the select element to be relative to the input-group. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css ...