Click on <div> to focus <input> (React) [closed]

I know how to do this with jquery. But I am stuck with React: How would I focus an input field, whenever the user clicks on a div?

Answers:

Answer

You need to have an onClick event on the div and the call the focus() function on the input element that you can access by refs in react

class App extends React.Component {
  
  render() {
    return (
      <div>
          <div onClick={() => {this.myInp.focus()}}>Focus Input</div>
          <input type="text" ref={(ip) => this.myInp = ip} />
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

In the above snippet ref={(ip) => this.myInp = ip} is a callback approach of declaring refs which is recommended by react-docs

Answer

Check this https://facebook.github.io/react/docs/refs-and-the-dom.html

Via ref you can anything jquery-like.

Answer

try this:

var Hello = React.createClass({
    getInitialState: function() {
        return {
            value: 1,
            editMode: false
        };
    },
    edit: function() {
        this.setState({editMode: true});
    },
    handleChange: function(event) {
        this.setState({value: event.target.value});
    },
    focusInput(component) {
        if (component) {
            React.findDOMNode(component).focus(); 
        }
    },
    render: function() {
        if (true === this.state.editMode) {
            return (
                <input 
                  ref={this.focusInput} 
                  type="text" 
                  value={this.state.value} 
                  onChange={this.handleChange} />
            );
        }
        return (
            <div>The value is: <span>{this.state.value}</span> 
                <button onClick={this.edit}>
                    Edit
                </button>
            </div>
        );
    }
});

React.render(
    <Hello name="World" />, 
    document.getElementById('container')
);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.