Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form input gets unfocused after typing in 1 character. #1853

Closed
Industrial opened this issue Sep 23, 2016 · 6 comments
Closed

Form input gets unfocused after typing in 1 character. #1853

Industrial opened this issue Sep 23, 2016 · 6 comments

Comments

@Industrial
Copy link

Hi. I'm trying to implement bootstrap style inputs with redux-form. Whenever I start typing into an input like this; it will unfocus the input after 1 character. When I re-select it and continue typing it works normally. It also works normally when I just use component="text".

              <Field
                name="surname"
                component={({ input, meta }) => {
                  return (
                    <div>
                      <input type="text" className="form-control" {...input}/>
                    </div>
                  )
                }}
              />
@Industrial Industrial changed the title Form input gets unfocusedafter typing in 1 character. Form input gets unfocused after typing in 1 character. Sep 23, 2016
@Pisi-Deff
Copy link
Contributor

Not 100% sure but:

Since you're declaring the component as an inline arrow function, the function's signature/reference will be different each time it is rendered.
When you input data into the input, the Field's state changes => it rerenders => component is different => it rerenders => "loses focus" because old element that had focus no longer exists.

Likely solution, (untested, no guarantees):
Declare the function in the React component:

  renderComp({input, meta}) {
    return (
      <div>
          <input type="text" className="form-control" {...input}/>
       </div>
     )
  }

  render() {
              <Field
                name="surname"
                component={this.renderComp}
              />
  }

@Industrial
Copy link
Author

You are correct :-)

closing this ticket

@michaelnagy
Copy link

michaelnagy commented Jul 7, 2017

This solution didn't work for me. Just saying. This is my component:
https://gist.github.com/michaelnagy/a400e9b243553da8e0ce094a0855b2a1

@Pisi-Deff
Copy link
Contributor

@michaelnagy

Took your code, replaced all the functions/components it didn't include with dummies:
https://jsfiddle.net/75rh036o/43/

No loss of focus problems.

So it must be that some of the logic you didn't include is causing the <input>'s to be rerendered while you're typing.

Feel free to make the jsfiddle code into a more complete example so the problem can be analyzed further.

@softwarefactory1
Copy link

I had the same problem with an html table in which I have input text lines in a column. inside a loop I read a json object and I create rows in particular I have a column with inputtext.

        http://reactkungfu.com/2015/09/react-js-loses-input-focus-on-typing/

        I managed to solve it in the following way


    import { InputTextComponent } from './InputTextComponent';
    //import my  inputTextComponent 
    ...

var trElementList = (function (list, tableComponent) {

var trList = [],
    trElement = undefined,
    trElementCreator = trElementCreator,
    employeeElement = undefined;



// iterating through employee list and
// creating row for each employee
for (var x = 0; x < list.length; x++) {

    employeeElement = list[x];

    var trNomeImpatto = React.createElement('tr', null, <td rowSpan="4"><strong>{employeeElement['NomeTipologiaImpatto'].toUpperCase()}</strong></td>);
    trList.push(trNomeImpatto);

    trList.push(trElementCreator(employeeElement, 0, x));
    trList.push(trElementCreator(employeeElement, 1, x));
    trList.push(trElementCreator(employeeElement, 2, x));

} // end of for  

return trList; // returns row list

function trElementCreator(obj, field, index) {
    var tdList = [],
        tdElement = undefined;

    //my input text
    var inputTextarea = <InputTextComponent
        idImpatto={obj['TipologiaImpattoId']}//index
        value={obj[columns[field].nota]}//initial value of the input I read from my json data source
        noteType={columns[field].nota}
        impattiComposite={tableComponent.state.impattiComposite}
        //updateImpactCompositeNote={tableComponent.updateImpactCompositeNote}
    />

    tdElement = React.createElement('td', { style: null }, inputTextarea);
    tdList.push(tdElement);


    var trComponent = createClass({

        render: function () {
            return React.createElement('tr', null, tdList);
        }
    });
    return React.createElement(trComponent);
} // end of trElementCreator

});
...
//my tableComponent
var tableComponent = createClass({
// initial component states will be here
// initialize values
getInitialState: function () {
return {
impattiComposite: [],
serviceId: window.sessionStorage.getItem('serviceId'),
serviceName: window.sessionStorage.getItem('serviceName'),
form_data: [],
successCreation: null,
};
},

    //read a json data soure of the web api url
    componentDidMount: function () {
        this.serverRequest =
            $.ajax({
                url: Url,
                type: 'GET',
                contentType: 'application/json',
                data: JSON.stringify({ id: this.state.serviceId }),
                cache: false,
                success: function (response) {
                    this.setState({ impattiComposite: response.data });
                }.bind(this),

                error: function (xhr, resp, text) {
                    // show error to console
                    console.error('Error', xhr, resp, text)
                    alert(xhr, resp, text);
                }
            });
    },

    render: function () {
...
React.createElement('table', {style:null}, React.createElement('tbody', null,trElementList(this.state.impattiComposite, this),))
...
}



        //my input text
        var inputTextarea = <InputTextComponent
                    idImpatto={obj['TipologiaImpattoId']}//index
                    value={obj[columns[field].nota]}//initial value of the input I read //from my json data source
                    noteType={columns[field].nota}
                    impattiComposite={tableComponent.state.impattiComposite}//impattiComposite  = my json data source

                />//end my input text

                tdElement = React.createElement('td', { style: null }, inputTextarea);
                tdList.push(tdElement);//add a component

    //./InputTextComponent.js
    import React from 'react';

    export class InputTextComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          idImpatto: props.idImpatto,
          value: props.value,
          noteType: props.noteType,
          _impattiComposite: props.impattiComposite,
        };
        this.updateNote = this.updateNote.bind(this);
      }

    //Update a inpute text with new value insert of the user

      updateNote(event) {
        this.setState({ value: event.target.value });//update a state of the local componet inputText
        var impattiComposite = this.state._impattiComposite;
        var index = this.state.idImpatto - 1;
        var impatto = impattiComposite[index];
        impatto[this.state.noteType] = event.target.value;
        this.setState({ _impattiComposite: impattiComposite });//update of the state of the father component (tableComponet)

      }

      render() {
        return (
          <input
            className="Form-input"
            type='text'
            value={this.state.value}
            onChange={this.updateNote}>
          </input>
        );
      }
    }

@lock
Copy link

lock bot commented Mar 29, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators Mar 29, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants