Home > Enterprise >  "onFocus" prop is not changing properly between two text fields
"onFocus" prop is not changing properly between two text fields

Time:10-29

I need to move the cursor from textfield1 to textfield2 when I press the "Enter" from textfield1 and I need to move the cursor from textfield2 to textfield1 when I press the "Enter" from textfield2.
States are changing properly when I press "Enter" from textfield2 and textField2, but the cursor doesn't move between text fields.

Here is my code.

export default class BasicTextFields extends React.Component {
  constructor(props) {
    super(props);
    this.one = this.one.bind(this);
    this.two = this.two.bind(this);

    this.state = {
      one: true,
      two: false,
    };
  }

  one(e) {
    console.log(e.key);
    if (e.key == 'Enter') {
      this.setState(
        {
          two: true,
          one: false,
        },
        () => {
          console.log(this.state);
        }
      );
    }
  }

  two(e) {
    if (e.key == 'Enter') {
      this.setState(
        {
          two: false,
          one: true,
        },
        () => {
          console.log(this.state);
        }
      );
    }
  }

  render() {
    return (
      <Box>
        <TextField
          onKeyDown={this.one}
          autoFocus={this.state.one}
          id='filled-basic'
          label='Filled'
          variant='filled'
        />

        <TextField
          onKeyDown={this.two}
          autoFocus={this.state.two}
          id='standard-basic'
          label='Standard'
          variant='standard'
        />
      </Box>
    );
  }
}

CodePudding user response:

For DOM manipulations, as for managing the focus of input elements, you can use React Refs.

Using React Refs — assuming your refs are called respectively inputOne and inputTwo — you will be able to call this.inputTwo.current.focus() to put the focus on the second input. For information, the property current of the Ref returns the HTML DOM node.

One more thing to keep in mind is, since your <input> tags are in a children component, but you need to control focus from the parent of both inputs, you'll have to declare the refs in the parent, and forward the references thanks to React.forwardRef. See also Forwarding Refs.

Here is the demo

  • Related