How to cross out (Strikethrough) Text in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Photo from Unsplash

Cross out (Strikethrough) Text in React #

Use the textDecoration property to strikethrough text in React, e.g. <span style={{textDecoration: 'line-through'}}>. The text-decoration CSS property sets the appearance of decorative lines on text.

App.js
const App = () => { return ( <div> <h2> <span style={{textDecoration: 'line-through'}}>Hello</span> world </h2> </div> ); }; export default App;

react strikethrough text

If you need to cross out an element on click, check out my other article - Cross out (Strikethrough) text on Click in React.

We used the text-decoration property to cross out text in React.

Notice that multi-word properties are camelCased when specified as inline styles.

The first set of curly braces in the inline style marks the beginning of an expression, and the second set of curly braces is the object containing styles and values.

App.js
<span style={{textDecoration: 'line-through'}}>Hello</span> world

When the textDecoration property of an element is set to line-through, it's text is crossed out.

If you need to do this often, you can extract the span element into a component which renders its children.

App.js
function StrikethroughText({children}) { return <span style={{textDecoration: 'line-through'}}>{children}</span>; } const App = () => { return ( <div> <h2> <StrikethroughText>Hello</StrikethroughText> world </h2> </div> ); }; export default App;

This code sample achieves the same result. Whatever we pass between the opening and closing tags of the StrikethroughText component will have the its text crossed out.

An alternative solution is to define a strikethrough class in a global css file.

App.css
.strikethrough { text-decoration: line-through; }

And here is how we would import the App.css file and use the strikethrough class.

App.js
import './App.css'; const App = () => { return ( <div> <h2> <span className="strikethrough">Hello</span> world </h2> </div> ); }; export default App;

This approach enables us to reuse commonly used styles by defining them in a global css file.

It's a best practice to import your global css files in your index.js file because then they wouldn't only get loaded when certain component is mounted.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.