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

Transform all characters to lowercase, then capitalize them using only CSS

I came across a discussion on this topic at: First lowercase the text then capitalize it. Is it possible with CSS? However, the solution provided was not purely based on CSS. I have a div that contains the following text: <div> RaWr rAwR </div&g ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

Narrowing Down State Types

I am working on a functional component in NextJS with props passed from SSR. The component has a state inside it structured like this: const MyComponent = ({err, n}: {err?: ErrorType, n?: N})=>{ const [x, setX] = useState(n || null) ... if(e ...

Utilize ReactJS, Axios, and PHP to fetch the latest information from the database

I am facing an issue where the data on my page does not update when I make changes to the database. The initial data is rendered correctly, but any subsequent changes are not reflected on the page even after calling the update function. The PHP function o ...

Ways to utilize the data received from getServerSideProps in the page?

I need some help understanding how to access data fetched in a Next.js page using GraphQL/Apollo and Typescript. The page exports a function called getServerSideProps. When I log the props, I can see the data, but it's in an unusual format with the id ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Ways to protect your ExpressJS RESTful API from unauthorized access

Is it possible to enhance security for an expressjs RESTful API so that only a react native app and react website have access? For example, the server runs on port 8000, the react native app is on port 3000, and the website on port 5000. It’s desired th ...

Ways to rejuvenate a React component following a call to the backend Node application?

I am managing an application that consists of: React frontend Node JS + Express backend Mongo DB The communication between the backend and frontend relies heavily on Apollo GraphQL. Recently, I have integrated Twilio for making calls. Once a call is made ...

Chrome is failing to run the keyframe animation transform

This solution seems to function properly on Firefox and Safari, and even on IE! However, it encounters issues when used on Chrome. (It runs smoothly on Firefox and IE, but on Chrome the animation does not display at all!) @keyframes animationFrames{ 0% ...

"Utilizing lightbox JS to produce a centralized overlay across the entire webpage

Currently in the process of redesigning a gallery for a client at www.stagecraft.co.uk/gallery.html I am encountering some challenges with my overlay. I want it to be centered and on top of any divs that are currently in view, as new images from the clie ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

The never-ending dilemma of React: should we alter the state array or leave it in its original

My question is regarding state mutations. I came across a suggestion on Cannot see updates from child component through parent's callback (case array and push) that mutating state directly is not recommended. As demonstrated in https://codepen.io/jad ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

How can text be concealed within an input field?

My degrees converter code is functioning well, but I have an issue. When I input a number for one temperature type, the conversion for the other two types is displayed correctly. However, if I then enter a number for another temperature type, the previous ...

Navigate through the Jquery slider by continuously scrolling to the right or simply clicking

Is there a way to prevent my slider from continuously scrolling? I think it has something to do with the offset parameter but I'm having trouble figuring it out. Any assistance would be greatly appreciated. var $container = $(container); var resizeF ...

Tips for setting a Bootstrap 3 dropdown menu to automatically open when located within a collapsed navbar

Is there a way to have my dropdown menu automatically open when the collapsed navbar is opened? Take a look at this example I created in a fiddle to see what I'm working with so far. Right now, when you click on the navbar in its collapsed state, two ...