Giter Site home page Giter Site logo

react-input-autosize's Introduction

React-Input-Autosize

A text input for React that resizes itself to the current content.

Demo & Examples

Live demo: jedwatson.github.io/react-input-autosize

To run the examples locally, run:

npm install
npm start

Then open localhost:8000 in a browser.

Installation

The easiest way to use React-Input-Autosize is to install it from NPM and include it in your own React build process (using Browserify, rollup, webpack, etc).

You can also use the umd build by including dist/AutosizeInput.js in your page. If you use this, make sure you have already included a umd React build.

npm install react-input-autosize --save

Usage

React-Input-Autosize generates an input field, wrapped in a <div> tag so it can detect the size of its value. Otherwise it behaves very similarly to a standard React input.

import AutosizeInput from 'react-input-autosize';

<AutosizeInput
	name="form-field-name"
	value={inputValue}
	onChange={function(event) {
		// event.target.value contains the new value
	}}
/>

Gotchas

Changing the styles at runtime

The styles applied to the input are only copied when the component mounts. Because of this, subsequent changes to the stylesheet may cause size to be detected incorrectly.

To work around this, either re-mount the input (e.g. by providing a different key prop) or call the copyInputStyles() method after the styles change.

CSP and the IE "clear" indicator

The input will automatically inject a stylesheet that hides IE/Edge's "clear" indicator, which otherwise breaks the UI. This has the downside of being incompatible with some CSP policies.

To work around this, you can pass the injectStyles={false} prop, but if you do this I strongly recommend targeting the input element in your own stylesheet with the following rule:

input::-ms-clear {display: none;}

Custom font sizes

If your input uses custom font sizes, you will need to provide the custom size to AutosizeInput.

<AutosizeInput
	name="form-field-name"
	value={inputValue}
	inputStyle={{ fontSize: 36 }}
	onChange={function(event) {
		// event.target.value contains the new value
	}}
/>

Uncontrolled input

AutosizeInput is a controlled input and depends on the value prop to work as intended. It does not support being used as an uncontrolled input.

License

Copyright (c) 2018 Jed Watson. MIT License.

react-input-autosize's People

Contributors

caedmon avatar callumlocke avatar costagolub avatar d4goxn avatar danilvalov avatar dantman avatar dominiklessel avatar flenter avatar gimite avatar gwyneplaine avatar i-like-robots avatar ivoba avatar jedwatson avatar jochenberger avatar krainboltgreene avatar marvwhere avatar methuselah96 avatar miracle2k avatar mvf4z7 avatar nagaozen avatar paulpooch avatar quentin- avatar ranneyd avatar rkkautsar avatar sdemjanenko avatar srph avatar uiur avatar wehriam avatar wmertens avatar yoiang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-input-autosize's Issues

MS EDGE - the input first character is shown cut

I've tried on your demo page also.
It seems to be a bug on IE 11, that the size in pixels is different on inputs that on divs, so when it refreshes the input size it becomes not as big as it should and remains shorter than the div child.

A possible solution I think is to change the make the container listen to the width in pixels and set the input width to 100% so it will grown to fit the container and have the correct width

Thanks

screenshot_1

Release >= 0.6.3 breaks server side rendering

Error:

ReferenceError: window is not defined
    at ...\node_modules\react-select\node_modules\react-input-autosize\lib\AutosizeInput.js:10:6
    at Object.<anonymous> (...\node_modules\react-select\node_modules\react-input-autosize\lib\AutosizeInput.js:16:3)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (...\node_modules\react-sel
ect\lib\Select.js:11:13)
    at Module._compile (module.js:456:26)

Problem appeared in react-select after having it reinstalled recently. It's dependency to react-input-autosize is specified as ^0.6.2 or ^0.6.0. This is quite unfortunate, since there's no easy way to fix react-select by downgrading a minor version: Every version is broken in this respect now...

React 15.2 breaking changes

Related issue
JedWatson/react-select#1073

react-select is broken cause react-input-autosize is not capatible with React 15.2
Warning: Unknown propminWidthon <input> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop in input (created by AutosizeInput) in div (created by AutosizeInput) in AutosizeInput (created by Select) in div (created by Select) in div (created by Select)

Styles from input not being copied to hidden div

I noticed that font related styles from the visible input were not being properly copied to the hidden div used for calculating the size. This was causing the size of the input to be incorrect (too large), as the font-size of the div was larger than that of the input.

After changing this line to return when the compoennt is NOT mounted it seemed to fix the issue

e.g. if (!this.mounted || !window.getComputedStyle) {

Div or no div

In your textarea component, I believe there is no surrounding div, but in this component there is. Just a bit of an inconsistency which slightly complicates things in my app where I use both.

Server-side rendering window undefined

There is an issue when page is pre-rendered server-side.

error given was: ReferenceError: window is not defined
    at \node_modules\react-select\node_modules\react-input-autosize\lib\AutosizeInput.js:10:9
    at Object.<anonymous> (\node_modules\react-select\node_modules\react-input-autosize\lib\AutosizeInput.js:13:3)
    at Module._compile (module.js:460:26)
    at Module._extensions..js (module.js:478:10)
    at Object.require.extensions.(anonymous function) [as .js] (\node_modules\babel-core\lib\api\register\node.js:214:7)
    at Module.load (module.js:355:32)
    at Module._load (module.js:310:12)
    at Function.module._load (\node_modules\piping\lib\launcher.js:32:16)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (\node_modules\react-select\lib\Select.js:13:13)
    at Module._compile (module.js:460:26)
    at Module._extensions..js (module.js:478:10)
    at Object.require.extensions.(anonymous function) [as .js] (\node_modules\babel-core\lib\api\register\node.js:214:7)
    at Module.load (module.js:355:32)
    at Module._load (module.js:310:12)

input style.width not correctly set for minWidth='5px'

The PropType for minWidth states that either string or number is valid.
react-select passes '5px' for minWidth.
But props.minWidth is used to set state.inputWidth in a way that is only valid if minWidth is a number, both in getInitialState() and updateInputWidth().
Then render() unconditionally appends 'px' to state.inputWidth to set inputStyle.width.
So in the case of minWidth='5px' you get inputStyle.width='5pxpx' which React apparently converts to '2px'. Set minWidth='5' and you get the expected '5px' width.

While it would be easy enough to fix this for the 'px' case, I think the comparison in updateInputWidth() would make it more difficult to handle other units on minWidth, e.g. '%' or 'em'.

Simply taking away the string option for minWidth would fix react-input-autosize and would cause a warning in react-select and others that are passing string values.

Add support for placeholder

If a placeholder property is set, it will be ignored and cropped.

The component should detect the placeholder and reset the minWidth value to its size.

unknown props on input tag

giving the props inputClassName and minWidth to the component causes an error on the console
because the input tag is getting them with {..props}
and input tag is not expecting them.
thank you for helping.

New React throwing errors on component

Warning: Unknown prop `minWidth` on <input> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop
    in input (created by AutosizeInput)
    in div (created by AutosizeInput)

Missing dependencies for `create-react-class` and `prop-types`

Hey,
My build is failing because of a recent update of this library.

Log -

Error: Cannot find module 'create-react-class'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function._resolveFilename (/home/uv/dev/t2k-js-common/node_modules/mocha-webpack/lib/util/registerRequireHook.js:42:34)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/uv/dev/t2k-js-common/node_modules/react-input-autosize/lib/AutosizeInput.js:7:19)
    at Module._compile (module.js:571:32)
    at Module._extensions..js (module.js:580:10)
...

Seems like you added usage to a library but forgot to add it to dependency\peer dependency.
Thanks in advance.

Auto focus by default

I had a query regarding autofocus in this component.

I have used the autofocus component in my project. I was wondering how can i have the AutoSizeInput to have a default onFocus state. Currently if i click on it it gets the focus

Width problem when using css box-sizing: border-box

It would be great if it could automatically detect the box-sizing of the

and figure out the correct width.

My current workaround is adding a className to the Element and target the box-sizing of the

used by the component.

The gulp dev task deletes all the built files when they change

The gulp task for development isn't set up correctly, it deletes all the built files when one of the watch tasks run.

This is due to limitations with orchestra that will be solved in Gulp 4, but for now is a real pain. The whole gulp file needs to be reworked to fix this, or the clean tasks need to be removed (which I would prefer not to do)...

One possible solution is to create duplicate tasks with dist and dev versions, where the dist versions all depend on the clean task, and the dev ones don't.

inputStyle with textTransform

If inputStyle has textTransform style (textTransform: uppercase), it should be passed to the internal div style, as it changes the width. I'm using this control with react-select and having this problem.

Breaking changes in new PATCH version `1.1.3`

Could you please release new major version or move prop-types from devDependencies to dependencies or peerDependencies?

Because we have an error:
Error: Cannot find module 'prop-types'

1.1.2+ standalone build is broken

Hi,

Previously standalone build worked with React.min.js etc. (though the readme states this was not supported), but with 1.1.2 and later, the standalone build tries to call require, which doesn't work: https://jsfiddle.net/3ov0m5x5/

react-input-autosize.js:1 Uncaught Error: Cannot find module 'react'
    at s (react-input-autosize.js:1)
    at react-input-autosize.js:1
    at Object.2../factory (react-input-autosize.js:742)
    at s (react-input-autosize.js:1)
    at react-input-autosize.js:1
    at Object.<anonymous> (react-input-autosize.js:1875)
    at Object.14.create-react-class (react-input-autosize.js:2031)
    at s (react-input-autosize.js:1)
    at e (react-input-autosize.js:1)
    at react-input-autosize.js:1

no-op in copyInputStyles when a component is mounted

Here is the check in copyInputStyles:

	copyInputStyles () {
		if (this.mounted || !window.getComputedStyle) {
			return;
		}

The copyInputStyles is called right after this.mounted is set to true in compomentDidMount. Shouldn't the condition be !this.mounted instead?

        componentDidMount: function componentDidMount() {
                this.mounted = true;
                this.copyInputStyles();
                this.updateInputWidth();
        },

Width problem for placeholder

I'm using AutosizeInput with TagsInput and these inputProps:

inputProps={{
  className: 'react-tagsinput-input',
   placeholder: 'Add a theme',
}}

The props that are actually passed to AutosizeInput are:

type='text'
onChange={onChange}
value={value}
className : "react-tagsinput-input"
onBlur: ()
onFocus: ()
onKeyDown: ()
onPaste: ()
placeholder: "Add a theme"
ref: "input"

My problem: on initial render, when 'value' is empty, the input box is only a couple of pixels wide. I believe this is because the computation of 'sizerValue' in the AutosizeInput render function does not consider the placeholder.

As a temporary fix, I added the following. But it's a hack because (a) it does not consider that the font could be wider or narrower, and (b) it defeats the autosizing function for tags that are shorter than 90 px.

minWidth: 90

Prevent input from changing line height and content width

I'd like to create an input that is visually equivalent to a span with different background color, meaning it does not change the line height or is wider than the span with exactly the same text.

This is my attempt, works for the above but is not ideal.

    const style = {
      fontFamily: 'inherit',
      fontSize: 'inherit',
      height: '1em',
      lineHeight: '1em',
      border: '1px',
      borderColor: '#DDF',
      borderStyle: 'solid solid solid none',
      margin: '0px 0px 0px 0px',
      padding: '0px 0px 0.15em 0px',
      minWidth: 30 > width ? 30 : width,
      width: inputText != '' ? inputWidth : width,
      backgroundColor: '#EEF',
      display: 'inline-block',
      whiteSpace: 'nowrap',
    }
...
        <div
          contentEditable
          style={style}
          value={inputText}
          onChange={this.handleOnChange}
          onKeyPress={(e) => {if(e.which == 13) e.preventDefault()}}
        />

Any way to achieve the same with react-input-autosize?

Support for input[type="number"]

Browsers like Chrome display controls for number inputs:

screen shot 2016-07-27 at 11 25 21

This results into some parts of the number being hidden. Is there a good way to solve this? The screenshot shows an input field where I entered 123.

Cursor lagging input in Safari

I originally found this issue in the react-select component and reported it on this ticket.

Now I've recorded the same behaviour on the demo page of this project as well.

react-input-autosize_cursor_lag

When typing at a reasonable speed the cursor seems to be lagging the input of the component. However the input is still OK. However when typing fast the input might actually get compromised.

We have a bunch of other components using the same "controlled value" mechanism where this is not happening.

This was recorded with the latest Safari on OSX. We do not see this on latest Chrome.

Strange resizing behavior in a modal in Safari (seems to be calculating widths slightly too small)

We are using the react-select 1.0 beta version

In our modal ( from fastmodel-layout-components http://fastmodelsports.github.io/fastmodel-layout-components/ ) we are seeing strange behavior with the select where the input doesn't resize to the correct width and wraps

screen shot 2016-06-08 at 12 36 22 pm
screen shot 2016-06-08 at 12 36 16 pm
screen shot 2016-06-08 at 12 36 11 pm
screen shot 2016-06-08 at 12 36 06 pm

The same selector outside the modal appears to work
screen shot 2016-06-08 at 12 40 01 pm

As far as I can tell all the font settings are the same

Any idea what might be going on here?

IE-specific -ms-clear styling breaks CSP

The inline style element used by the -ms-clear workaround breaks Content Security Policy. Would it be possible to have an extra prop that would control whether such a workaround is applied (I don't believe the current approach can be made CSP-safe)?

(Extra note: both the element and the style element refers to state.id which should probably be state.inputId which is defined in the constructor).

this.refs.input is not of type element

Hi, I'm trying to use your excellent-looking react-select library and am running into a bug. When I instantiate a Select field on the page for the first time, AutosizeInput is failing with the following error from line 46 of the AutosizeInput.js file:

Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

I tried debugging by replacing the this.refs.input with a this.refs.input.getDOMNode() so it would get past that error, but similar issues sprang up with this.refs.sizer on the following lines. Even when I replaced them both, the same error'd reference to this.refs.input was breaking throughout the file. I wasn't sure if replacing all of them was the best approach.

The project is using React 0.14.0, I'm not sure what could be going wrong. The field itself, by the way, is rendering completely wonky:
image

Thoughts?

EDIT: I tried replacing every single this.refs.[...] in the file with this.refs.[...].getDOMNode() and was able to get rid of errors, but the input still didn't render correctly. It did show all provided options in a dropdown and let me select them, but everything was unstyled and I got these error messages:

Warning: React can't find the root component node for data-reactid value .0.1.0.3.2.0.0.0:$packageForm-2.0.1.1.2. If you're seeing this message, it probably means that you've loaded two copies of React on the page. At this time, only a single copy of React can be loaded at a time.

ReactMount.js?ed21:710 Uncaught TypeError: Cannot read property 'firstChild' of undefined

ie11 invalid calling object

I get an Invalid Calling Object error on IE11 on line 67:

queueUpdateInputWidth: function queueUpdateInputWidth() {
    nextFrame(this.updateInputWidth);
}

After debugging I found that nextFrame equal to requestAnimationFrame, and binding nextFrame to window correct the issue.
I will open a PR to fix this.

Infinite loop in Safari

Yosemite 10.10.5
Safari 8.0.8 (10600.8.9)

I had an issue that causes Safari hang.
I'm sorry it's hard to reproduce in general case. But I would like to share my workaround for someone in the future.

The issue was that scrollWidth of the sizer changes by 1px after state.inputWidth is updated.

scrollWidth of the sizer is affected by state.inputWidth, so this causes infinite state updates like this.

this.state.inputWidth newInputWidth
1 40
40 41
41 40
40 41
41 40
... ...
if (newInputWidth !== this.state.inputWidth) {
 this.setState({
   inputWidth: newInputWidth
 });
}

It might be a bug in Safari.

Workaround

My workaround is ignoring 1px error. I know this is not a good solution, but works well for now.

if (Math.abs(newInputWidth - this.state.inputWidth) > 1) {
 this.setState({
    inputWidth: newInputWidth
 });
}

uiur@4370bd5

I think this case is rare, so feel free to close this issue.

update to React 14 syntax, with a new major version?

There is a closed PR for uplifting the code for React 14, which now that it's the official release (and has been for a few months) is a great idea to land and then tag as 1.0.0, with that major version bump so that people who rely on 0.4.* don't have any of their tools autoupdate to it.

Can't access the click area of the input field

This might be an implementation error but our the input field is not clickable.
Here's the implementation

<form
  className="foo-FontSizeControl"
  onSubmit={this.handleSubmitOrBlur}>
  <label>
    <AutosizeInput
      id="fontIconWidth"
      className="foo-Input"
      name="width"
      onBlur={this.handleSubmitOrBlur}
      onChange={this.handleWidthChange}
      onKeyDown={this.handleKeyDown}
      value={this.state.iconWidth}
      type="number"
      step={FORM_INPUT_STEPPER}
    />
    {'"'}
  </label>
  <span className="foo-FontSizeControl-label1">x</span>
  <label>
    <AutosizeInput
      id="fontIconHeight"
      className="foo-Input"
      name="height"
      onBlur={this.handleSubmitOrBlur}
      onChange={this.handleHeightChange}
      onKeyDown={this.handleKeyDown}
      value={this.state.iconHeight}
      type="number"
      step={FORM_INPUT_STEPPER}
    />
    {'"'}
  </label>
</form>

With the label wrapper, I actually can click over where the " is. It appears that the label element is what's clickable in my app and it just pokes out from under the input element.

Any advice is greatly appreciated.

Debounced input misses typed characters in IE11

When using an asynchronous handler with the onChange event in IE11, it's possible for characters to be skipped so that the input value does not reflect what was typed.

This is technically a bug in React itself:
facebook/react#7027

Though React will fix the bug in version 16.0, this remains a huge problem for our IE users until then. We hope you'll consider using the onInput event internally instead of onChange, which should resolve the issue (we've tried it out locally and it works great). We'd be happy to submit a PR for this if desired.

Incomplete HTML escaping in sizer DIV

Just insert "foo<b>bar</b>" in an input field and the size calculation will be off. This is because you're using dangerouslySetInnerHTML without fully escaping the input.

HTML codes not properly sized

If you type foo bar &quot; into the box, then the &quot; becomes a quote behind the scenes and doesn't occupy as much space as it should in the input.

Can I load this package from CDN?

I tried to find a CDN link for this package, but I couldn't. Please let me know if you know the way to load this package from CDN. Thanks.

Uncaught TypeError: Cannot read property 'scrollWidth' of undefined

Hi,
I'm using your react-select component but it keeps throwing errors. But I think the real problem is here.

First error shown is
Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).

And then following
Uncaught TypeError: Cannot read property 'scrollWidth' of undefined
which appears in updateInputWidth() function in AutosizeInput component in the first condition

typeof this.refs.sizer.scrollWidth === 'undefined'

Here is listing of npm ls | grep react to show you versions I'm working with

โ”œโ”€โ”ฌ [email protected]
โ”œโ”€โ”€ [email protected]
โ”œโ”€โ”ฌ [email protected]
โ”œโ”€โ”ฌ [email protected]
โ”‚ โ””โ”€โ”€ [email protected]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.