Paragraph featuring keywords highlighted by categoryIn this text, we will be analyzing different categories

I am looking to implement a visual feature similar to the image below using react js. Can anyone provide guidance on how to accomplish this? I have a collection of words categorized as Organization, Person, and Location. My goal is to assign different colors to these words based on their category.

https://i.sstatic.net/c3gWU.png

Although I have tried the code below, it did not produce the desired outcome:

<text style={{background:"#A6E22D", borderRadius: "5px", color:'#1E1935'}}> By signing up, you agree to Terms of Service and </text><br/>

Answer №1

If you want to incorporate the feature described, one way to do it is by segmenting your text into blocks that match and don't match your specified keywords. You can then style the matching blocks using <span> tags:

const { useState } = React,
      { render } = ReactDOM,
      rootNode = document.getElementById('root')

const srcText = `Amazon and Facebook are encouraging their employees in Seattle to stay home after workers for each company tested positive for the novel coronavirus.
Amazon (AMZN) revealed earlier this week that one of its Seattle-based employees has been diagnosed with the virus. On Wednesday, Facebook said a contractor who works at one of its offices in Seattle had tested positive.`

const sampleKeywords = [
  {word: 'Amazon', tag: 'ORG'},
  {word: 'Facebook', tag: 'ORG'},
  {word: 'Seattle', tag: 'GEO'},
  {word: 'earlier this week', tag: 'TIME'},
  {word: 'on Wednesday', tag: 'TIME'}
]

const TaggedText = ({text, keywords}) => {
  const rawKeywords = keywords.map(({word}) => word),
        markedText = text.replace(new RegExp(rawKeywords.join('|'), 'gi'), w => `|${w}|`),
        textBlocks = markedText.split('|').filter(textBlock => textBlock.length != 0)
  return (
    <span style={{lineHeight:'160%'}}>
      {
        textBlocks.map((textBlock,key) => {
          const tag = (keywords.find(({word}) => word.toLowerCase() == textBlock.toLowerCase()) || {tag: null}).tag
          return <span {...{key,...(tag && {tag})}}>{textBlock}{tag && <span className="tagLabel">{tag}</span>}</span>
        })
      }
    </span>
  )
}

render(<TaggedText text={srcText} keywords={sampleKeywords} />, rootNode)
span.tagLabel {
  background: #fff;
  border-radius: 3px;
  font-size: 10px;
  font-weight: bold;
  margin-left: 10px;
  color: grey;
}

span[tag="ORG"] {
  background: #bf405c;
  padding: 2px 10px;
  border-radius: 5px;
  color: #fff;
  white-space: nowrap;
}

span[tag="GEO"] {
  background: #3a8a2e;
  padding: 2px 10px;
  border-radius: 5px;
  color: #fff;
  white-space: nowrap;
}

span[tag="TIME"] {
  background: #822e8a;
  padding: 2px 10px;
  border-radius: 5px;
  color: #fff;
  white-space: nowrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

using mixins with styled-components

I have encountered a challenge while attempting to pass a mixin from Material UI to a styled-component. The problem lies in finding a way to transfer the mixin value to the styled-component without having to assign it to a css property. Unfortunately, dire ...

Redirect in ExpressJS after a DELETE request

After extensive searching, I am still unable to figure out how to handle redirection after a DELETE request. Below is the code snippet I am currently using WITHOUT THE REDIRECT: exports.remove = function(req, res) { var postId = req.params.id; Post.re ...

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Ways to showcase an array with HTML content in AngularJS without using ng-repeat

Can someone help with this coding issue? "elements" : ["<p>Element 1</p>","<span>Element 2</span>"] I want to achieve the following output: <div id="wrapper"> <p>Element 1</p> <span>Element 2</s ...

What is the best way for me to create a test for GTM tracking?

Currently, I am in the process of developing an application using NextJS/React and I have integrated GTM for tracking customer events. One specific event I am tracking is when a customer clicks on the 'Add to Cart' button on the product page. Wh ...

Adjustable Bootstrap Progress Bar - Modify element width on the fly

I have encountered an issue with my progress bars on the webpage. The static HTML version works perfectly fine, but the dynamically created one using jQuery seems to be instantly at 100% without any delay in progression. To illustrate the problem better, ...

Emphasize user management and interaction in C# programming

In my master page, there is a user control (error control) that is initially hidden (visible set to false). When the submit button is clicked, I show the error control. After postback, I want to focus on this control. To achieve this, I am writing JavaScr ...

Building a React Yarn project within a docker container usually requires over 5 minutes to complete

It's taking over 5 minutes to execute a yarn build for my relatively small codebase. Below is my dockerfile, excluding yarn installation with node-modules: ### STAGE 1: Build FROM node:14.17.0-alpine as build WORKDIR /app COPY . . RUN yarn install ...

Sending property value to computed properties within a component

Is it considered a best practice to utilize a prop value within a computed property function of a component? If so, how can I construct the return statement using this prop? Carousel.vue props: [ 'source', ], computed: { items () { re ...

Is there a way to stop the onRowClick event from being triggered when an action button in custombodyrender is clicked?

I am currently working with a mui-datatable where the onRowClick function navigates the user to another page. Each row also has a custom action button. However, when clicking the custom action button, it also triggers the onRowClick function which redire ...

Enhancing text visibility in dompdf by making it bold or increasing its size

Recently, I began using dompdf v0.6.0beta3 along with the dompdf Codeigniter helper in Codeigniter. To address the issue of missing fonts, I manually moved the Arial font family tff files from the Windows 7 font folder to the /lib/fonts directory within do ...

Determining the exact position of an absolute element within a Bootstrap container

In my design, I am using a full-width cover image with a bootstrap container class containing an absolutely positioned image on top of the cover image. My goal is to have this image positioned exclusively on the right-hand side of the container. Below is ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

How can I speed up the loading time of my background image?

I have noticed that my background image is loading slowly on my website. I expected it to be cached so that subsequent pages using the same background would load instantly. However, the background image is only loading once the entire page is drawn. My CS ...

Trouble arises with the chrome extension code for retrieving tweets from Twitter

I'm currently working on developing a Chrome extension that will display tweets featuring the hashtag perkytweets within the extension's popup. However, I'm facing an issue where nothing is being displayed. Let's take a look at the cod ...

How can I create a Material ui Card with a border-less design?

After reviewing the information provided, I noticed that you can set the option to have it as variant="outlined" or raised However, I am curious if there is a method to create the card without any visible borders at all? ...

Client event triggered twice by server

Hey there! I'm currently working on creating a simple chat app using socket.io and express. One issue I'm facing is that when a user sends a message, the server broadcasts it to the rest of the clients, but it seems to be happening twice. I can& ...

PHP code isn't showing any posts

Context: I have implemented a PHP loop to generate a dynamic feed of my portfolio posts on my WordPress website. Issue: The first five posts are being displayed correctly, but the subsequent posts are not. I'm uncertain about the underlying cause and ...

Are you in favor of side-to-side scrolling?

I can't quite recall where I've encountered this concept before, but I do know that there must be a method for creating a horizontal scroll. Imagine you have multiple DIVs in the following structure: <div class="container"> <div> ...

Multiple buttons in a single field

I am attempting to replace a Dropdown list with a series of buttons that will streamline the choices previously displayed by the dropdown list. Specifically, we are using graphic png files for the types of buttons. We experimented with checkboxing and ra ...