Combining two flex elements with auto-growing capabilities in react-native

I am excited about using react-native to have a TextInput aligned with a MaterialIcons.Button in the same line. I have been trying to center these elements horizontally but haven't been successful with the code below:

import React from 'react';
import {
  StyleSheet, TextInput, View,
} from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';

const WordInput = () => {
  return (
    <View style={styles.container}>
      <View style={styles.textInputContainer}>
        <TextInput
          textAlign="left"
        />
      </View>
      
      <View style={styles.arrowButtonContainer}>
        <MaterialIcons.Button
          name="arrow-forward-ios"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    flex: 1,
  },
  textInputContainer: {
    flex: 1,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  arrowButtonContainer: {
    flex: 1,
    alignItems: 'flex-start',
    justifyContent: 'center',
  },
});

You can view the code on expo snack link.

The issue I'm facing is that when I type in the TextInput, the Button does not move at all. I want it to shift dynamically to the right as the TextInput's width grows while keeping everything horizontally centered.

If anyone has any suggestions on how to proceed, I would greatly appreciate it!

Thank you!

Answer №1

Unfortunately, the <TextInput> component does not have built-in support for auto-growing behavior. However, you can create this functionality yourself by utilizing a hidden <Text> element that mirrors the styling of your <TextInput>. By rendering the input value to the hidden <Text> element, you can measure its layout and apply the width to the <TextInput> component.

import { useState } from 'react';
import { StyleSheet, TextInput, View, Dimensions, Text } from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';

export default function App() {
  const [value, setValue] = useState();
  const [containerWidth, setContainerWidth] = useState(
    Dimensions.get('window').width
  );
  const [textWidth, setTextWidth] = useState(0);
  const [buttonWidth, setButtonWidth] = useState(0);

  const inputWidth = Math.min(textWidth, containerWidth - buttonWidth);

  return (
    <View style={styles.root}>
      <View
        style={styles.inner}
        onLayout={(e) => setContainerWidth(e.nativeEvent.layout.width)}>
        <Text
          style={styles.hiddenText}
          onLayout={(e) => setTextWidth(e.nativeEvent.layout.width)}
          numberOfLines={1}
          accessibilityElementsHidden
          importantForAccessibility="no-hide-decendants">
          {value}
        </Text>
        <TextInput
          textAlign="left"
          placeholder="enter text"
          style={[styles.input, { width: inputWidth }]}
          onChangeText={setValue}
        />
        <View onLayout={(e) => setButtonWidth(e.nativeEvent.layout.width)}>
          <MaterialIcons.Button name="arrow-forward-ios" />
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    flex: 1,
    justifyContent: 'center',
  },
  inner: {
    flexDirection: 'row',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'red',
  },
  input: {
    borderWidth: 1,
    borderColor: 'green',
    minWidth: 100,
  },
  hiddenText: {
    position: 'absolute',
    top: 0,
    left: 0,
    opacity: 0,
  },
});

You can view a demonstration of this implementation in this expo snack example.

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

Modify styling of complete list upon clicking in React

For my latest project, I developed a basic todo application using React. One of the key features is that when a user clicks on a checkbox, the corresponding todo item's CSS changes to show a strike-through effect. Additionally, a button appears on hov ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Is there a way to have a fixed width div positioned in the center of the screen, with two additional divs on either side

I have come across this stunning image: https://i.stack.imgur.com/tUYMc.png It serves as a header for a website - click on it to see the full size. I am trying to replicate this using HTML, CSS, and images, but I'm struggling. It needs to be 100% w ...

The nested CSS grid is failing to show its nested elements on the page

Having trouble with a nested CSS GRID - the child grid items are not appearing correctly despite multiple checks on the markup. The first grid row should span three columns, as it does, and is set to display:grid with 2 child grid items. However, the chil ...

Circular css3 animation originating from the center

Can someone provide an example of how to create a div rotating around a circle in CSS3 while the circle itself is already rotating? I attempted to use webkit frame, but it did not work correctly. If anyone has any examples or tips on achieving this effec ...

Is it possible to leverage Apple Pay within the Expo app to create a unique payment token?

Is it possible to utilize Apple Pay within the Expo app to produce a payment token without having to eject and switch to React Native? I anticipated that the payment token would be generated using the React Native payment package, but unfortunately Expo G ...

Aligning the .left position to make the border of a <div> synchronized

When working on my Jquery program, I encountered an issue with borders not aligning properly within the container. Specifically, in the execution (where the container is represented by a white box), the left border extends beyond the position().left proper ...

CSS table row border displaying irregularly in Chrome and Internet Explorer

I recently created a basic table with bottom row borders. Surprisingly, the borders display perfectly in Firefox but only partially in Chrome and IE 10: <div style="display:table; border-collapse: collapse; width: 100%"> <div style="display:table ...

Expanding the width of three floating divs in the center to match the width of the parent container div

In my design, I have a parent container with three inner divs that are floated. The left and right divs have fixed sizes, however, I need the center div to expand and fill the space available within the parent container. <div class="parent-container"&g ...

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

Implementing CSS keyframes when a specified PHP condition is satisfied

I am looking to implement an opening animation on my website that should only play when a user visits the site for the first time. I want to avoid displaying the animation every time the page is reloaded, so it should only run if a cookie indicating the us ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

How can I remove a specific JSON object from localStorage based on the data associated with the element that is currently being clicked on?

Unique Scenario A user interacts with an element, triggering a change in the background image and storing data related to that element in localStorage: this process functions correctly. Next, the toggle variable is set to 0, the background image change ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Toggle visibility with JQuery's onClick event

I am looking for a way to toggle the visibility of text that has display: none; in CSS when a button is clicked, as well as clear the input field on the onClick event. Currently, the text remains visible even after it has been displayed. Any assistance wou ...

Inherit margins from child elements with fixed positions

Below is a very basic code example to consider: <div id="parent"> <div id="child"> Test it </div> </div> This code snippet includes the following CSS styles: #parent{ position:relative; margin-left:200px; color:#FFF; } #chi ...

Optimizing mobile page layouts with CSS

I'm putting in a lot of effort to ensure that my simple form page is optimized for mobile devices. Although the form is visible, I find myself having to zoom in quite a bit in order to read it. Here's an example: ...

Having trouble initializing a React Native project using npm/expo start?

After consulting the react-native documentation to create an android app, I followed these steps: npm install -g expo-cli After running the above command in my project file, I used the following commands: expo init first-proj cd first-proj Everything se ...

Utilizing CSS to Target IDs Using Classes

Recently, I came across a captivating video on YouTube demonstrating how to create a transitional gallery (http://www.youtube.com/watch?v=4sVTWY608go). Inspired by the tutorial, I attempted to implement a similar slider... However, I now have a new idea. ...

Ways to align elements horizontally while preventing them from shifting positions

I'm faced with a layout challenge where I need to place 2 components side by side, but I want one component to stay on the right without affecting the orientation of the other component. Example: https://i.stack.imgur.com/T5Ram.png Currently, when I ...