Cross out (Strikethrough) text on Click in React


Borislav Hadzhiev

Last updated: Apr 24, 2022


Photo from Unsplash

Cross out (Strikethrough) text on Click in React #

To cross out text on click in React:

  1. Set the onClick prop on the element.
  2. When the element is clicked, check if its text-decoration property is set.
  3. If the property is set, remove it, otherwise set it to line-through.
const App = () => { const handleClick = event => { if ( {'text-decoration'); } else {'text-decoration', 'line-through'); } }; return ( <div> <p onClick={handleClick}>Walk the dog</p> <br /> <p onClick={handleClick}>Buy groceries</p> </div> ); }; export default App;

react strikethrough on click

We set the onClick on the paragraph elements, so every time they are clicked, the handleClick function is invoked.

The target property on the event object refers to the specific paragraph tag that was clicked.

We first check if the textDecoration property is set in the element's style object.

If the property is set, we use the removeProperty method to remove it.

If the textDecoration property is not set, we use the setProperty method to cross out the text.

This has the effect of toggling the strikethrough style on the paragraph tags.

You can set the onClick prop on as many elements as necessary and use the same handleClick function because it uses the event object ot get a reference to the element that was clicked.

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.