I have a Input component which takes an <input>
element and renders it. It is a div, containing a label and an input.
My boss asked me that when I click anywhere in the div, it focuses on the input (so if it's a dropdown, it opens the dropdown, input, we can start writing text, etc).
I was thinking of doing it using refs: when an user clicks on the div, an onClick element is trigerred and the input gets focuses.
However, all the input are in this.props.children
. How can I put a ref on the input and use it in my code? Here's what it looks like:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tooltip } from '@material-ui/core';
export class Input extends Component {
displayTitle () {
if (this.props.tip) {
return (
<label htmlFor={this.props.name} className="lone-input-container-title">
{this.props.title}<Tooltip placement="top" arrow title={this.props.tip}><span className="shadow-md p-1 text-hardbacon rounded-full px-2 cursor-pointer ml-2">?</span></Tooltip>
</label>);
}
return (
<label htmlFor={this.props.name} className="lone-input-container-title">
{this.props.title}
</label>
);
}
render () {
return (
<div className="lone-input-container">
{this.displayTitle()}
<div>
{React.cloneElement(this.props.children[0])}
</div>
</div>
);
}
}
Input.propTypes = {
name: PropTypes.string,
title: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
tip: PropTypes.string
};
export default Input;