I need to obtain text selection data from Material-ui's TextField. Text selection data must include selection start, selection end, and the selected text.
I managed to get as far as the following using createRefs
import React, { createRef } from "react";
import { TextField, Button, Box, Grid } from "@material-ui/core";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selStart: undefined,
selEnd: undefined,
selValue: undefined
};
this.onSaveSelectionClicked = this.onSaveSelectionClicked.bind(this);
this.textFieldRef = createRef();
}
onSaveSelectionClicked(ev) {
// Somehow obtain selection start, end, and value
// then update state
const { selectionStart, selectionEnd, value } = this.textFieldRef.current;
this.setState({
selStart: selectionStart,
selEnd: selectionEnd,
selValue: value.substring(selectionStart, selectionEnd)
});
}
render() {
return (
<Box p="2em">
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
name="essay1"
label="Essay 1"
multiline
rows={3}
fullWidth
inputRef={this.textFieldRef}
/>
</Grid>
<Grid item xs={12}>
<TextField
name="essay2"
label="Essay 2"
multiline
rows={3}
fullWidth
inputRef={this.textFieldRef}
/>
</Grid>
<Grid item xs={12}>
<Button variant="contained" onClick={this.onSaveSelectionClicked}>
Save selection
</Button>
</Grid>
<Grid item xs={12}>
<pre>{JSON.stringify(this.state)}</pre>
</Grid>
</Grid>
</Box>
);
}
}
Which gives me the following
The problem is, this doesn't seem to work with multiple TextField. The current property of the refs will always refer to 'Essay 2' text field.
Are there better way to approach this problem?
Here's the link to codesandbox for the above code
