Create a bolded section within a TextField component using Material UI version 5

I am working with a TextField component that has a specific defaultValue set. Here is the code snippet:

  <TextField
      autoFocus={props.autoFocus}
      fullWidth
      defaultValue={props.defaultValue}
      value={text}
      onKeyPress={handleKeyPress}
      onFocus={(e) => e.target.select()}
      onChange={handleChange}
  />

Some parts of the default value are enclosed in parentheses, and I want to make these parts bold while keeping the rest as it is. Does anyone know how I can achieve this?

Answer №1

If you need to include HTML in the label attribute dynamically, you can use the following function. While the MUI TextField defaultValue and value attributes do not support inline HTML, the label attribute does:

const htmlParser = (text) => {
  let i = 0;
  let l = 0;
  let renderables = [];
  let html = '';

  for (i = 0; i < text.length; i += 1) {
    if (text[i] === ' ') {
      renderables.push(text[i]);

      if (text[i + 1] === '(') {
        let isHtmlFound = false;
        while (!isHtmlFound) {
          for (l = i + 2; l < text.length; l += 1) {
            if (text[l] !== ')') {
              html = html.concat(text[l]);
            } else if (text[l] === ')') {
              isHtmlFound = true;
              break;
            }
          }
        }
        renderables.push(
          <strong>
            {html}
          </strong>,
        );
        html = '';
        i = l + 1;
      }
    }
    renderables.push(text[i]);
  }
  return renderables;
};

Now you can include HTML in your component label like this:

<TextField label={htmlParser('use (label) and (not) defaultValue')} ... />

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

What is the best way to remove a parent app.js element from a child component?

When I click the delete button, my intention is to filter an array in the parent app.js component and remove a specific item. However, I keep encountering a Typescript error stating Cannot assign to read only property 'message' of object 'Sy ...

Efficiently rendering a million elements on an HTML canvas (and replicating the render from the server)

I'm currently working on developing an HTML application using a canvas as the base. The canvas will consist of a large grid, around 1500 x 700 in size, totaling to over 1 million cells. The main concern is how to efficiently render this grid without ...

Retrieve the information transmitted to an EJS file within a separately included JavaScript file

I'm currently utilizing express js to render a file by using: res.render('plain',{state:'admin'}) The file plain.ejs includes main.js: <script src ="/main.js"></script> I need assistance on how to access the state v ...

View / Conceal Unordered List depending on link selected

How can I dynamically show or hide UL elements based on the clicked link? Here is a JS Fiddle example: http://jsfiddle.net/zangief007/rj8g0yh4/1/ Below is the HTML code: <ul class="category-1 group"> <li class="name">JOHN Smithe QC</l ...

The <img> tag is displaying with dimensions of 0 x 0 pixels even though its size was specified

Is there a way to control the image size within an <img> tag placed inside an html5 video element? Currently, it keeps defaulting back to 0 x 0 pixels. The reason behind using this img is to serve as a fallback for outdated browsers where the video ...

Using React to dynamically display API data on your website

My objective is to extract data from the Google API and showcase the information in a DOM element. Following a helpful guide at : https://medium.com/swlh/combat-toxicity-online-with-the-perspective-api-and-react-f090f1727374 The form is functional and su ...

Update the style of the legend from bars to a line chart in chart.js version 2.4.0

https://i.sstatic.net/BXcXj.pngI'm currently using chart.js version 2.4.0 for displaying graphs, and I'm having trouble changing the legend style from bar to line. Is there a way to switch the legend display from bar to line in chart.js? Here i ...

Is there a way to include multiple div elements on a single page using React?

I am currently in the process of developing an e-commerce website and I am looking to display multiple items on the front end using React.js with Bootstrap as the CSS library. Below is the code snippet for my return div. How can I go about showcasing mul ...

The Step-by-Step Guide to Adding a Function Style to Wordpress

Typically I would use enqueue in this manner wp_enqueue_style( 'mystyle', get_stylesheet_directory_uri() . '/css/style.css',false,'1.1','all'); but now I have created a custom field and need to enqueue a style that ...

Submit a HTML form to a Telegram recipient

I am looking to send HTML form data, which includes input values and select options, to a telegram user. After some research, I discovered that I need to create a Telegram bot. I successfully created one using @botFather by following these steps: /newbot ...

Interacting between Angular controllers and directives while maintaining separation of concerns

In my AngularJS project, I've implemented a directive within a module named ThreeViewer that displays WebGL scenes based on the specified source file. The code snippet below outlines the basic functionality: angular.module('ThreeViewer', [] ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

Is it possible to format correctly using React-Intl without encountering this particular error message?

Currently, I am working on enhancing a React Native application where the post_date retrieved from a third-party API needs to be presented as: x many days ago, instead of appearing as 2019-05-10 11:26:39. In an attempt to achieve this, I explored utilizin ...

Guide on importing all exported functions from a directory dynamically in Node.js

In my file main.ts, I am looking to efficiently call imported functions: import * as funcs from './functions'; funcs.func1(); funcs.func2(); // and so forth... In the same directory as main.ts, there is a functions directory containing an index ...

What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript fun ...

Utilizing AJAX and JavaScript to generate a table using the AJAX response and placing it within a <div> element

I am currently passing the response of this action in text form, but I would like to display it in a table format. Is there a way to do this? function loadAditivos(){ $('#aditivoAbertoInformacoesTexto').html('<div id="loaderMaior ...

Having trouble uploading an image to AWS using Angular and NodeJS?

I am currently working on a Node/Express application and I need to gather file information for uploading from an Angular/Ionic front end. To achieve this, I have created a separate Service in Angular that successfully retrieves the Image name. However, my ...

I am receiving a 401 error when attempting to verify the token following a successful login

I've been working on a small project utilizing VueJS, Vue Router, and Laravel for the backend. Despite several attempts, I haven't been successful in implementing navigation guards. My login component is functioning properly. Here's my log ...

React js is not displaying the image

Currently, I am working on developing an application using Spring Boot for the backend and React.js for the frontend. Within my database, I have fields for "title," "image," and "content." When fetching data without using the frontend, all details includin ...

photos arranged in rows rather than a single row

Looking for help with arranging the remaining photos in the second row? Check out this example image link. I'm struggling to organize a row of overflow images within the "small-img-row" division. This row is located under the main image in col-2. H ...