I need to trigger click on <TextField>
of material-UI manually on certain event. In React I'd have been creating a ref
and then triggered onClick
on that ref. How do I achieve this in React Hooks?
P.S In case you're wondering, why I need to do this, this is why: Material UI - The textfield in the search bar doesn't get clicked when search icon is clicked
I need to trigger click on <TextField>
of material-UI manually on certain event. In React I'd have been creating a ref
and then triggered onClick
on that ref. How do I achieve this in React Hooks?
P.S In case you're wondering, why I need to do this, this is why: Material UI - The textfield in the search bar doesn't get clicked when search icon is clicked
Share Improve this question asked Sep 25, 2020 at 18:24 ABGRABGR 5,2754 gold badges34 silver badges55 bronze badges3 Answers
Reset to default 2You cannot simply assign a ref
prop to the TextField
and call it a day like what the other answers have described. ref
only works on DOM elements such as <input/>
. In a custom ponent you would normally need to use Forwarded Refs.
However, in your case, since you are using MUI TextField
, they already expose a prop that enables you to attach the ref
to its internal input
element. The prop is inputRef
.
function App() {
const txtField = React.useRef(null);
return(
<div>
<Button
variant="contained"
color="primary"
onClick={() => {
txtField.current.focus()
// at this point if you need to trigger click then invoke .click() instead
}}>
focus on text field
</Button>
<br/>
<TextField inputRef={txtField} />
</div>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<body>
<div id="root"></div>
<script src="https://unpkg./react@16/umd/react.development.js"></script>
<script src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg./babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg./@material-ui/core@latest/umd/material-ui.development.js"></script>
<script type="text/babel">
const { TextField, Button } = MaterialUI;
</script>
</body>
Use react hook named useRef
then pass the ref created to ref attribute or innerRef attribute.
const ref=React.createRef();
//click
ref.current.onclick=
<TextField ref={ref}/>