Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native to limit lines in TextInput

Tags:

react-native

If set multiline as true, React Native will accept unlimited lines in TextInput, there has maxLength but it just limits the maximum number of characters, so how to set maximum lines on TextInput?

like image 981
Justin Avatar asked Mar 30 '17 20:03

Justin


People also ask

How do I limit characters in TextInput React Native?

To set max length of the TextInput with React Native, we can set the maxLength prop. to set the maxLength prop to 10 to allow users to enter a max of 10 characters into the input.

How do you set the number of lines in TextInput in React Native?

You can use maxHeight and minHeight to accept what you want. For standard text fontSize, giving maxHeight={60} will make TextInput scrollable after 3 lines. This is good for IOS - for Android you can use numberOfLines prop.


2 Answers

You can use maxHeight and minHeight to accept what you want. For standard text fontSize, giving maxHeight={60} will make TextInput scrollable after 3 lines. This is good for IOS - for Android you can use numberOfLines prop.

like image 101
David Avatar answered Oct 09 '22 05:10

David


I created a simple version to extend the TextInput to give the maxLines feature.

import React, { Component } from "react";
import { TextInput } from "react-native";
import PropTypes from "prop-types";

export default class MultiLine extends Component {
  static propTypes = {
    maxLines: PropTypes.number
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value || ""
    };
  }

  onChangeText = text => {
    const { maxLines, onChangeText } = this.props;
    const lines = text.split("\n");

    if (lines.length <= (maxLines || 1)) {
      onChangeText(text);
      this.setState({ value: text });
    }
 };

 render() {
   const { onChangeText, multiline, value, ...other } = this.props;
   return (
     <TextInput
       {...other}
       multiline={true}
       value={this.state.value}
       onChangeText={this.onChangeText}
     />
   );
 }
}

A example:

<Multiline
  value={this.state.testeText}
  maxLines={10}
  onChangeText={text => {
    this.setState({ testeText: text });                
  }}
/>
like image 32
Felipe R. Saruhashi Avatar answered Oct 09 '22 05:10

Felipe R. Saruhashi