EN
React - disable text selection
6
points
In this article, we would like to show you how to disable text selection in React.
Practical example
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.
// ONLINE-RUNNER:browser;
// Note: Uncomment import line in your project.
// import React from 'react';
const DisabledSelection = ({tag, style, children, ...other}) => {
const Tag = tag ?? 'div';
if (style) {
style = {...style, userSelect: 'none'};
} else {
style = {userSelect: 'none'};
}
return (
<Tag {...other} style={style} unselectable="on">
{children}
</Tag>
);
};
// Usage example:
const elementStyle = {
margin: '10px',
padding: '20px'
};
const element1Style = {
...elementStyle,
background: 'silver'
};
const element2Style = {
...elementStyle,
background: 'gold'
};
const App = () => {
return (
<div>
<DisabledSelection tag="div" style={element1Style}>
This text is not selectable ...
</DisabledSelection>
<div style={element2Style}>
This text is selectable ...
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );