EN
React - disable text selection
6 points
In this article, we would like to show you how to disable text selection in React.
In this example, we create a wrapping component that disables text selection by setting style - userSelect: 'none'
and property - unselectable="on"
. Then we use this component inside the App
.
xxxxxxxxxx
1
// Note: Uncomment import line in your project.
2
// import React from 'react';
3
4
const DisabledSelection = ({tag, style, children, other}) => {
5
const Tag = tag ?? 'div';
6
if (style) {
7
style = {style, userSelect: 'none'};
8
} else {
9
style = {userSelect: 'none'};
10
}
11
return (
12
<Tag {other} style={style} unselectable="on">
13
{children}
14
</Tag>
15
);
16
};
17
18
19
// Usage example:
20
21
const elementStyle = {
22
margin: '10px',
23
padding: '20px'
24
};
25
26
const element1Style = {
27
elementStyle,
28
background: 'silver'
29
};
30
31
const element2Style = {
32
elementStyle,
33
background: 'gold'
34
};
35
36
const App = () => {
37
return (
38
<div>
39
<DisabledSelection tag="div" style={element1Style}>
40
This text is not selectable ...
41
</DisabledSelection>
42
<div style={element2Style}>
43
This text is selectable ...
44
</div>
45
</div>
46
);
47
};
48
49
const root = document.querySelector('#root');
50
ReactDOM.render(<App />, root );