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

Using Javascript to retrieve form data from a separate file

I am struggling with my HTML and JavaScript files to collect data. Despite my efforts, the function is not executing properly. Below is the code I have been working on: HTML File : <form class="form-newsletter"> <div class="form-group"> ...

The blur() function does not function properly on IOS devices such as iPad and iPhone

I've attempted using blur() to change the CSS, but it seems that this function is not effective. After researching, I discovered that blur() does not work on IOS devices. Is there an alternative method for removing the position from .body-clip-overflo ...

How is the CSS selector affected by the presence of an asterisk (*)?

Take for instance the following code snippet: (I am familiar with using a star in CSS selectors, but not with '> *') .row > * { float: right; } And then there's this one: .row.uniform > * > :first-child { mar ...

Erase embedded frame from a Google Sheets document

Is there a way for me to customize the frame and replace it with my own design? Click here to view the Google Sheet embedded frame ...

3D Animation for All Browsers

I'm currently working on creating a small browser-based game and I've been experimenting with animations to get the desired effect. So far, the animation works well in Opera and Edge, although there is a slight cropping issue in Edge. Unfortunat ...

Interactive Map Using HTML5, CSS, and JQuery

As someone venturing into the world of web front end development, I am curious about the process of mapping an image so that specific functions can be triggered by pressing different parts. In this case, the shapes will be irregular (such as a map of Europ ...

Customize the appearance of semantic-ui-react components with hover effects

When I assign a specific className to components like <Segment className="Change" color='blue' inverted></Segment> and then in my CSS I apply the following: .Change:hover{ background-color: black; //or any other hover effect } N ...

Setting up Scss and purgeCss configuration in Next.js custom postCSS configuration: A step-by-step guide

My current project is using Scss in combination with Bootstrap for design. I have implemented purgeCss to remove unused Css, and customized my postcss.config.js file as follows: module.exports = { plugins: [ "postcss-flexbugs-fixes", [ " ...

Find a solution for displaying custom product badges

Having some issues with a custom product badge on my website. I tried adding a new badge (besides "Sale"), but it seems to be displaying in the wrong position. The badge should display as "Choice" on the featured products, so I added this code to the chil ...

Not all Angular Material2 styles are being fully applied

One issue I am encountering is that styles for components such as <mat-chip> or <button mat-raised-button> (the only ones I have found) are not working properly and appear gray by default. However, styles do apply correctly to the <mat-card& ...

Adjust the width of columns using HTML and CSS

UPDATED: Here is a real-life scenario I am facing: I am trying to adjust the width of columns in my table using inline CSS. Let me provide you with an example: The Table was initially set to 100%, like this: <table width=100% ...> The total number ...

Just a snippet of a webpage shown

My website focuses on online magazines. I'm looking for a way to selectively display specific parts of articles that are in regular HTML format with a global CSS stylesheet applied. There are no images, only text. How can I extract certain segments of ...

Is it best to stick with a static page size, or

While I typically design my webpages dynamically by determining the screen size and creating divs accordingly, I'm curious about the advantages of using a 'static' sizing approach (such as using pixels). Any insights on this contrasting meth ...

Padding located within a div tag

As a novice in the world of HTML and CSS, I have designed a birthday card with a desired 50/50 split down the center. Placing an image on the left side was successful, however when trying to add text to the right, it ended up too close to the center line. ...

Is it possible for CSS div to have a height of 100% when placed within fluid parents

When the parent div's height is set to 100%, you can also set the child to 100% and it will function correctly. However, if the parent's height is determined by its content, the height attribute does not work as expected. Are there any effective ...

Innovative Inter-Browser Link with a Distinct Shape

I am currently developing a web application that enables users to input content and then send it out to their phones. Everything is working smoothly, but I am facing an issue with the logo design. The logo in question is displayed as follows: On the left ...

The 3D Circle Flip feature on a certain webpage designed by Nordstrom is experiencing issues when viewed on Firefox

Click here to see a 3D Circle Flip effect. It works correctly in Chrome, but in Firefox the text does not change when flipping. ...

Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way ...

When you hover over them, chips transform their color

I am currently using a chip in my code and I would like to change its color when the mouse hovers over it. I attempted to achieve this by using: hover:{ backgroundColor: 'red', } In addition, I incorporated const StyledChip ...

Traverse div elements using jQuery and showcase the text within them

I've got a setup like the one below. I want to use jQuery to grab each link and display its href right below it. Instead of writing code for each div individually, I'm looking for a solution that works for all divs with the 'col' class, ...