A guide on applying bold formatting to a specific section of text in React

I have a collection of phrases structured like so:

[
    {
       text: "This is a sentence."
       boldSubstrings: [
           { offset: 5, length: 2 }
       ]
    }
]

My goal is to display each phrase as a line using the following format:

 lines.map(elem => <p>{elem.text}</p>);

Is there a way to style the specified words in bold (resulting in "This is a sentence.")? Any suggestions?

Answer №1

This code snippet is effective:

const strings = [
  {
     text: "Here is an example.",
     boldParts: [
         { start: 5, length: 2 },
         { start: 8, length: 1 }
     ]
  }
];

strings.map(({text, boldParts}) => {
  let previousStart = 0;
  const segmentedTexts = [];
  for (let part of boldParts) {
    segmentedTexts.push(text.substr(previousStart, part.start - previousStart));
    segmentedTexts.push(<b>{text.substr(part.start, part.length)}</b>);
    previousStart = part.start + part.length;
  }
  segmentedTexts.push(text.substr(previousStart));
  return <p>{segmentedTexts}</p>;
});

Resulting in:

<p>Here <b>is</b> <b>an</b> example.</p>

Answer №2

This particular element is designed to handle the task at hand. It shares similarities with the above answer, but I have personally crafted this version! The assumption here is that the bold segments are always in sorted order. Keep in mind that it does not perform any argument validation, so use caution!

function FormattedLine({ text, boldSubstrings }) {
  let position = 0;
  const fragments = [];

  boldSubstrings.forEach(({ offset, length }) => {
    if (position < offset) {
      const paragraph = text.substr(position, offset - position);
      fragments.push({ text: paragraph, isBold: false });
    }
    if (length) {
      fragments.push({ text: text.substr(offset, length), isBold: true });
      position = offset + length;
    }
  });

  if (position < text.length) {
    fragments.push({
      text: text.substr(position, text.length - position),
      isBold: false
    });
  }

  return (
    <p>
      {fragments.map(({ text: fragmentText, isBold }) =>
        isBold ? <b>{fragmentText}</b> : fragmentText
      )}
    </p>
  );
}

Answer №3

If you're looking to enhance text styling in React, consider using react-substring-styler. It seamlessly achieves the desired effects without causing any disruptions to your project's structure or how texts are stored.

To get started, install react-substring-styler by running:
npm install react-substring-styler
or
yarn add react-substring-styler

Here's an example of how you can use this library:

const text = "This text is going to be [bold]."

<ParsedText patterns={
     [{type: "squareBrackets", style: {fontWeight: "bold"}}]}>
       {text}
 </ParsedText>

For more information, visit https://github.com/pborgesjr/react-substring-styler or check out the package on NPM at https://www.npmjs.com/package/react-substring-styler

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

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Exploring the intricacies of JSON object retrieval

I'm currently working on a form that allows users to submit address details for a selected location. However, before submitting the form, I want to give the user the ability to preview the address that will be sent. The addresses are stored within a J ...

"The Material-UI ListItem component acts as a link, updating the URL but failing to render the expected

Seeking help for the first time on this platform because I am completely perplexed. I'm working on coding a navbar for my school project website using Material-UI's List component within the Appbar component. However, I have encountered two issu ...

Meteor encountered an error while trying to insert the data: Access has been denied. There are no validation rules set on this specific collection to allow the method '

Hey there! I've recently started working on a Meteor-React project and I'm facing an issue while trying to add a new object to an existing collection. The error mentioned in the title keeps popping up. Below is the component responsible for inse ...

When you assign the page results from the scrape-it npm to a variable, it will return a Promise with the status of "pending."

I recently downloaded scrape-it from NPM as a dependency and I'm trying to store the results in a variable instead of using a callback function. When I run the code snippet provided in the scrape-it documentation: var myVar = scrapeIt("http://ionicab ...

Finding the nth-level children using JQuery

Is there a way to select nth-level children in CSS/jQuery without using any ID or class references, only tag names? I know how to get first level children with the selector div#block > div. But I am looking for a solution to target deeper levels. & ...

Dynamic row height in Material-UI DataGrid adjusting based on text content

When working with the DataGrid, I'm struggling to find a way to adjust row heights based on the length of text in each cell dynamically. I thought about utilizing renderCell on the column containing longer text and incorporating the <Typography> ...

What is the process for specifying a method on a third-party class in TypeScript?

I'm facing a challenge while trying to extend a third-party class in TypeScript. The issue is that I am unable to access any existing methods of the class within my new method. One possible solution could be to redeclare the existing methods in a sep ...

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Is it possible to seamlessly incorporate a square image into a bootstrap background image slider without having to crop the image?

I've exhausted all the different solutions I've come across on other platforms to resolve this issue, but I'm still unable to find a fix. So here's what I'm struggling with: The problem I'm facing involves finding the correct ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

I am looking to export multiple 'Pure components'

Currently, I am developing an app using React Native and came across an unusual observation. For some reason, the following code throws an error unless I modify the last sentence to: export default MyButton3; I aim to export more than one pure component ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

SASS: incorporating loops within CSS properties

Is there a way to generate multiple values for a single property in CSS? background-image: radial-gradient(circle, $primary 10%, transparent 10%), radial-gradient(circle, $primary 10%, transparent 10%), radial-gradient(circle, $primary 10%, tr ...

form for submitting multiple data via Ajax

I am working with two forms (request and feedback) where I need to use jQuery Ajax to send the data. When a user submits a request, the subject line will display "Request". If they submit feedback, the subject line will display "Feedback". Here is my cur ...

A guide to testing redux API using Node.js

I'm diving into the world of nodejs and redux as a beginner. I managed to install node v7.10 on my computer. While reading through the Redux documentation, it mentioned that I should be able to test the action, reducer, and store API without a user in ...

jQuery Autocomplete API Issue: Undefined

I've been attempting to implement a basic text box using the jQuery API from DevBridge. I followed instructions in this video tutorial to create my code. However, despite properly declaring scripts before the JS code and ensuring proper mappings, I&a ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...