Styling JavaScript strings with CSS - JavaScript/CSS Integration

I am trying to display a tooltip on hover using the data-tip attribute, but I am facing limitations with it only accepting strings. As a workaround, I have adopted the following approach:

var title = "Hello World";
var online: "Last Online 2 mins ago".
    <div>
        <span data-tip={title +" \n " +online} data-tip-always>{title}</span>
    </div>

However, I am now encountering an issue on how to style {title} as bold and set {online} font-size smaller than {title}.

Here is my updated code:

const titles = `<span class="title">Hello</span>`;
const online = `<span class="online">You are online</span>` ;
<span data-tip={`${titles}\n${online}`} data-html="true" data-tip-always>{title}</span>

As a result, I am currently seeing this formatting:

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

Initially, I attempted to implement this in JSX to apply colors and fonts, however, I struggled to find a way to incorporate JSX/HTML within a data-tip. Is there a method to apply CSS styles directly to strings?

Thank you.

Answer №1

The data-tip attribute in React-tooltip can only accept strings, but you can use the data-for attribute to reference a <ReactTooltip> component that can contain any content:

var title = 'Hello World';
var online = 'Last Online 2 mins ago';

ReactDOM.render(
<div>
  <span data-tip data-for="unique-tooltip-id" data-tip-always>{title}</span>
  <ReactTooltip id="unique-tooltip-id">
    <div className="tooltip-title">{title}</div>
    <div className="tooltip-online">{online}</div>
  </ReactTooltip>
</div>,
document.getElementById("react")
);
.tooltip-title {
  font-weight: bold;
}

.tooltip-online {
  font-size: 80%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/wwayne/react-tooltip@master/standalone/react-tooltip.min.js"></script>

<div id="react" style="position:absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);"></div>

Please note that the snippet may only work properly in "full page" mode.

Answer №2

If you use es6 notation, you can turn it into a template string.

Define your variables like this:

const title = `<span class="title">Hello</span>`
const online = `<span class="online">You are online</span>`

Then update your code to include the variables inside the string:

<div>
   <span data-tip={`${title}\n${online}`} data-tip-always>{title}</span>
</div>

This way, you have the flexibility to interpolate any variables within the template string and easily access them from the Element.dataset.

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

The alignment of margins appears as intended in Opera, Chrome, and IE, but unfortunately it does not

I have exhausted all possible options, but I am still struggling to get this page to appear correctly in Firefox. When you click inside the square, a menu with images should display on the right side. It is properly aligned in every browser except for Fire ...

Dynamically Alter Notification Background

I have created a demo page with some code for a smart notification. The issue I am facing is that even though the CSS is initially set to black, I want to dynamically change it to a random color upon creation. When I try to do this in the inspector, it w ...

The error message "Property '...' is not found on the type 'ServerContextJSONValue'" pops up whenever I try to utilize the useContext() function

After creating a Provider and defining the type, I encountered a TypeScript error when using it with useContext(): "Property '...' does not exist on type 'ServerContextJSONValue'. I'm not sure what I am missing. Can anyone help me ...

Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components. If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in u ...

Implementing a special class for the currently selected navigation item as a solution to the Bootstrap limitation

I'm currently developing a website using Bootstrap, and I want to add a custom style to active navigation items by creating a backdrop effect instead of just changing the text color. Initially, I started with white text color for testing purposes, bu ...

"Develop an interactive feature with jQuery that dynamically generates and removes fields according to the option selected from a

Can someone provide suggestions on how to achieve the functionality of adding and deleting input fields based on a user's selection from a drop-down menu using jQuery? I have successfully added the input fields, but I'm facing some confusion rega ...

Error encountered: The Bootstrap Carousel function is causing a TypeError as e[g] is not defined

I am attempting to build a dynamic bootstrap carousel using my json data, and I have implemented jQuery-Template for rendering. Essentially, I am generating the carousel slider on-the-fly from my json data with the help of jQuery-Template. Here is a snippe ...

Ways to detect when the user begins typing?

There is an input box with a cross icon that clears the input when clicked. The icon is visible even when the box is empty, which may not make sense. It would be better to show the icon only when the user starts typing. How can I detect when the user start ...

invoke a module through a function- react

Utilizing functional components within my application, I initially faced a situation where a single component contained a significant amount of code. To improve organization and create reusable components, I decided to divide the original component into th ...

Squire.js failing to replace mock dependency while utilizing store

Exploring Squire.js as a dependency loader for RequireJS. Testing in a standard web browser environment to run unit tests. Attempting to utilize store to access my mocks, but struggling with preventing Squire from loading the actual module. The usage of m ...

Overlaying a Bootstrap Collapse onto an element

I have been working with Bootstrap 3 to create a responsive website, specifically focusing on my "portfolio." You can view the website and also see an interesting error by visiting this link: If you scroll down to the section labeled "Our models" and cli ...

confirmation message upon completing a form submission

<script> var remainingCredit = document.getElementById("cor_credit"); var remaining = document.getElementById("remain_credit"); function validateForm() { if (remaining.value < remainingCredit.value) { return conf ...

Arranging text in CSS for responsive design

One issue I encountered was setting a division on the webpage. When I try to minimize the browser, the division does not adjust properly to fit the screen: width:1300px; margin:0 auto; height:40px; ...

What is the best way to save the response data into an array outside of the current function in Node.js?

How can I efficiently store all the result data into an array called pImages? I am able to retrieve the results, but I believe using an async function would be more suitable. However, I am unsure of how to implement it. Any assistance would be greatly appr ...

Error: JSON data received from API does not match expected format (using react, express, and axios

I can't shake the feeling that this might be a duplicate... If it is, I'm having trouble locating the correct thread. Currently, I have an Express API (using mongoose) running on a server with a React front end. The API should be returning a JSO ...

npm Error: The installation script for [email protected] has encountered a failure

I encountered an error while attempting to execute "ionic start MyApp" in the Windows terminal. This is a new machine and I have already reinstalled nodejs and ionic, but the same error persists. Can someone lend a hand? npm WARN tar invalid entry & ...

Transferring information from a React application to a Node Express server

I'm having issues passing data from my React frontend to my Node/Express server using the onSubmit function. The data is not displaying in the console or on the page, and it simply shows up as "undefined." Can someone provide some assistance? App.js ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...

Navigate to a particular section in the webpage

There are a few div elements with the class .posts that each have an attribute data-id which corresponds to the ID in a MySQL database. <div class="posts" data-id="1"></div> <div class="posts" data-id="2"></div> If I want to scrol ...

Applying CSS selectors to target child elements within a select option

I am looking to apply a CSS selector only on select option child values. I have assigned an id to the selector and now I want to apply different CSS styles to each child (child 1, child 2, etc). <select name="options[81]" id="select_81" class="required ...