Aligning Text at the Center in Your React Native Application

I'm facing a few issues with my visualization:

  1. Despite aligning it to the center, the text on my first button is positioned at the right end of the button. How can I move the text 'login' to the center?

  2. Currently, the 'Sign Up Here' text is displayed in the middle of the screen. I would like it to be towards the end. However, when I adjust the marginTop value, the text disappears. For example, setting it to 20 only shows half of the text (in the middle of the screen). Increasing it further makes it disappear entirely.

  3. The Forgot Password text also appears on the left side even though it's aligned.

  4. The title 'My App' is not visible at all.

How can I resolve these minor issues?

<Container View style={styles.container}>
      <Text View style={styles.title}>
        Instaride</Text>
        <View style={{flex:1}}></View>
      <Form View style={styles.formInput}> 
            <Item floatingLabel>
              <Label View style={styles.labelText}>Username</Label>
              <Input 
              View style={styles.textInput}
              onChangeText={(textUname) => uname(textUname)}
              value={textUname}

          placeholder={'Username'}
          />
            </Item>
            <Item floatingLabel >
              <Label View style={styles.labelText}>Password</Label>
              <Input 
              View style={styles.textInput}
              onChangeText={(textPassword) => password(textPassword)}
              value={textPassword}
          placeholder={'Password'}
          secureTextEntry={true}
          />
            </Item>
          </Form>

            <Button View style={styles.button}
            onPress={() => navigation.navigate("Details")}>
              <Text>Login</Text>
            </Button>
            <Text View style={styles.forgotText}>
              Forgot Password?</Text>

          <Right>
            <Button hasText transparent onPress={() => navigation.navigate('Registration')}>
              <Text View style={styles.signupText}>
                Don't have an account? Sign Up Here</Text>
            </Button>
          </Right>
      </Container>
    );
  }
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#242625',
    paddingTop: getStatusBarHeight(),
  },
  title: {
    textAlign: 'center',
    fontSize: 22,
    color: 'white',
  },
  textInput: {
    color: 'white',
  },
  button: {
    marginTop: 15,
    backgroundColor: '#65c756',
    width: '70%',
    height: '6%',
    justifyContent: 'center',
    alignSelf: 'center'
  },
  forgotText: {
    marginTop: 15,
    justifyContent: 'center',
    textAlign: 'center',
    color: 'white',
  },
   signupText: {
    marginTop: 16,
    justifyContent: 'center',
    color: 'white',
  },
  labelText: {
    fontSize : 14,
  },
  formInput: {    
    borderBottomWidth: 1, 
    marginLeft: 20,   
    marginRight: 20, 
    marginTop: 40,  
  },
});

Answer №1

Latest Update:

Avoid using the Input View method, as it is not recommended.

The code snippet below has been tested in the Expo demo and works perfectly fine if you include the full attribute in the Button.


Explanation of the key points:

  1. There's no need for Left/Right; simply place it inside a View. The use of Left was causing issues previously.
  2. To ensure the Middle Part expands to fill the screen and pushes your "Sign Up here" link to the bottom, apply a style of flex: 1 to it.
  3. The "Forgot password" link is now centered on the screen.
  4. We utilized the function getStatusBarHeight and added padding equal to the statusBarHeight.

import * as React from "react";
import {
  Text,
  View,
  StyleSheet,
  Container,
  Form,
  Item,
  Label,
  Input,
  Button,
  Content
} from "native-base";
import { SafeAreaView } from "react-native";
import Constants from "expo-constants";
import { getStatusBarHeight } from "react-native-status-bar-height";

// Import local files or pure JavaScript modules from npm
import AssetExample from "./components/AssetExample";
import { Card } from "react-native-paper";

export default class App extends React.Component {
  render() {
    return (
      <Container
        View
        style={Object.assign(
          { ...styles.container },
          { marginTop: getStatusBarHeight() }
        )}
      >
        <Content contentContainerStyle={{ flex: 1 }}>
          <View>
            <Text style={styles.title}>Instaride</Text>
          </View>

          <View style={{ flex: 1 }}>
            <Form style={Object.assign({ ...styles.formInput }, { flex: 1 })}>
              <Item floatingLabel>
                <Label style={styles.labelText}>Username</Label>
                <Input style={styles.textInput} placeholder={"Username"} />
              </Item>
              <Item floatingLabel>
                <Label style={styles.labelText}>Password</Label>
                <Input
                  View
                  style={styles.textInput}
                  placeholder={"Password"}
                  secureTextEntry={true}
                />
              </Item>
              <Button
                full
                style={styles.button}
                onPress={() => navigation.navigate("Details")}
              >
                <Text>Login</Text>
              </Button>
            </Form>
          </View>

          <View>
            <Text View style={styles.forgotText}>
              Forgot Password?
            </Text>

            <Button
              hasText
              transparent
              onPress={() => navigation.navigate("Registration")}
              style={{ justifyContent: "center" }}
            >
              <Text style={styles.signupText}>
                Don't have an account? Sign Up Here
              </Text>
            </Button>
          </View>
        </Content>
      </Container>
    );
  }
}

const styles = {
  container: {
    flex: 1,
    backgroundColor: "#242625",
    borderWidth: 2,
    borderColor: "red"
  },
  title: {
    textAlign: "center",
    fontSize: 22,
    color: "white"
  },
  textInput: {
    color: "white"
  },
  button: {
    marginTop: 15,
    backgroundColor: "#65c756"
  },
  forgotText: {
    marginTop: 15,
    justifyContent: "center",
    textAlign: "center",
    color: "white"
  },
  signupText: {
    textAlign: "center",
    justifyContent: "center",
    color: "white"
  },
  labelText: {
    fontSize: 14
  },
  formInput: {
    borderBottomWidth: 1,
    marginLeft: 20,
    marginRight: 20
  }
};

For a temporary demonstration, visit this Expo link:

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

The properties '{ label: string; value: string; }' are required in type 'readonly never[]' for react-select, but they are missing

state = { groupPermissionValue: {label: '', value: ''}, } <Select instanceId="user-group" onChange={this.selectUserGroupOption} value={this.state.groupPermissionValue} options={this.state.groupPermission} i ...

Removing the Create React App sample in a production environment can be achieved by following these

I recently deployed a domain on a production server and noticed that every time I open it, the address bar shows "Install app: Create React app sample." Is there a way to remove this message? What changes should I make in my code? Any suggestions? //Clie ...

Error in Next.js using next-auth/react: "PrismaClient cannot be executed in the browser"

Currently, I am in the process of developing a Next.js application and implementing authentication using the next-auth/react package. One of the server-side functions I have created utilizes PrismaClient to retrieve information about the current user based ...

Extracting command line arguments and parameters from a string within a node application for a simulated terminal interface site

In my Next.js project at this source, I have a string called command and I need to extract all the arguments (if any) and parameters (if any) into an array and object, respectively. For example: const command = "login 'username' -p 'secret ...

Align title text to the right within the Material Design Card

I have implemented a Material Design (MDL) card to showcase numeric values in the title. However, I am facing an issue where the values are left aligned by default and I want them to be right aligned. Despite trying various styles, they are being ignored ...

Using CSS to position an element relative/absolute within text inline

Need help aligning caret icons next to dynamically populated text in a navbar menu with dropdown tabs at any viewport size. Referring to positioning similar to the green carets shown here: https://i.stack.imgur.com/4XM7x.png Check out the code snippet bel ...

The RMWC Select Component is having trouble showing the chosen value

I tried using the Select component from rmwc 5.6.0, but I'm facing an issue where the selected value is not being displayed. Interestingly, this code worked perfectly fine with rmwc 3.0.11. This is how I have implemented the component: <Select ...

An easy guide to animating multiple sections of progress bars individually in Bootstrap

My Bootstrap code successfully animates a section of progress bars when the user views it. However, it currently animates all progress bars on the page rather than just those in the viewed section. This means that when the user moves to another section, th ...

How to ensure scrollbar adjusts to increasing height when using scroll:auto?

My <div> element has the style property scroll:auto. Whenever text is added to the <div> and the content height exceeds the default height, I find myself having to scroll down in order to see the latest lines of text that have been added. What ...

The height of the container is not adjusted correctly after loading data via ajax which causes it to overlap with

My HTML code consists of a container with two columns (content and sidebar) and a footer. The content contains a horizontal list with li elements that are populated via ajax when the "Load More" button is pressed. I am using Bootstrap and testing on Chrome ...

Ways to Design ASP.NET Buttons for Users with Disabilities

Recently, I attempted to style an asp button using CSS. The Button HTML: <asp:Button ID="btnClockin" runat="server" Text="Clock In" class="FullWidthButton" /> Here is the CSS code: .FullWidthButton {width:100%;} Everything was working fine until ...

What is the best way to modify the state of a particular element in an array when using useState in React?

In my Next.js application, I am using a useState hook to manage state. Here is how my initial state looks like: const [sampleData, setSampleData] = useState({ value1: '', value2: '', value3: [] }); To update the state ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

Are Css3 Transition and Transform properties dysfunctional in older versions of IE?

Snippet of HTML Code: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/demo.css" /> </head> <body> <div></div> </body> </html> CSS Snippet: div { width: 100p ...

Within the .module.scss file, there exist multiple classes that are identical; however, only one classname is reflected

How can I differentiate elements with the same class name? :S In Next.js, only one column1 is generated for each end cell1, cell2 class, etc.. Is there a way to solve this??: className={styles.left.column1}, className={styles.left.column1.cell1}, className ...

Attempting to update the state variable by combining data from various API calls

Today, I delved into the exciting world of the Google Maps API for the first time. After some perseverance, I finally succeeded in getting the map to render on the screen. Now, my focus is on adding markers for locations sourced from elsewhere in my applic ...

Navigating with React in ES5

My email addresses are "[email protected]" and "[email protected]". I am facing an issue with the following minimal example code: var React = require('react'); var ReactDOM = require('react-dom'); var Router = require(' ...

Stop the WebGL Three.js container from capturing scroll events

I am working on a full-screen three.js application which serves as the background and I am trying to add overlaid text that can be scrolled. However, my issue arises from the fact that the three.js WebGL container intercepts all scroll events and prevents ...

What is the best method to display a Component in React and reset its lifecycle whenever it is shown?

As a beginner in node.js and react, I decided to embark on the journey of creating a chat app using socket.io. I followed some tutorials on setting up rooms, joining/leaving them, and messaging within the rooms. To pass one socket instance, I utilized Reac ...

Conceal the Angular Bootstrap modal instead of shutting it down

I am utilizing Angular Bootstrap Modal to launch multiple modals, including a video player. http://angular-ui.github.io/bootstrap/#/modal My goal is to maintain the video's current position even when the modal is closed. This way, when I reopen the ...