Deathlex
Deathlex

Reputation: 184

How to set focus on button in componentDidMount

i have this component

class XY extends Component {
    constructor(props) {
        super(props)

        this.state = {
            open: false
        }
    }

    componentDidMount() {
        if(this.state.open === false && this.props.data.active === 1) {
            this.button.focus()
        }
    }

    render() {
        return (
            <div>
                <button ref={c => (this.button = c)}>
                    button
                </button>
            </div>
        )
    }
}

I need to set focus on rendered button after component mounts and under some conditions, but it doesn't work for some reason. I tried to set it up in componentDidUpdate and it worked but not on first render obv. Is there anything I've done wrong?

Thanks for help

Upvotes: 0

Views: 286

Answers (1)

Rohit Verma
Rohit Verma

Reputation: 3785

You need to use refs callback to focus on input button.

class XY extends React.Component{
  componentDidMount(){
    this.focusInput.focus();
  }
  render() {
    return(
      <div>
        <input type="button"
          ref={(input) => { this.focusInput = input; }} 
          defaultValue="button"
        />
      </div>
    );
  }
}
    
ReactDOM.render(<XY />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="root"></div>

Upvotes: 3

Related Questions