Languages
[Edit]
EN

React - disable text selection

6 points
Created by:
Giles-Whittaker
739

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 );

 

See also

  1. CSS - how to disable text selection?

  2. HTML - how to disable text selection?

References

  1. user-select - CSS: Cascading Style Sheets | MDN

Alternative titles

  1. React - how to disable text selection?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join