Enhancing the appearance of specific text in React/Next.js using custom styling

I have a table and I am currently working on implementing a search functionality that searches for an element and highlights the search terms as they are entered into the search bar. The search function is functional, but I am having trouble with the highlighting aspect.

My goal is to apply custom styling to the text inside my array.map conditionally based on the input state or render custom elements with specific styling. Below is the relevant code (with comments):

 <Table className={styles.table}>
            <thead>
                <tr>
                    <th>Description</th>
                    <th>Date and time</th>
                    <th>Debit</th>
                    <th>Credit</th>
                    <th>Balance</th>
                </tr>
            </thead>
            <tbody>
                {input.length < 1 ? displayTransactions.map(transaction => (
                    <tr key={transaction._id}>
                    <td>{transaction.description}</td>
                    <td>{transaction.date}</td>
                    <td className={styles.debit}>- ${transaction.debit}</td>
                    <td className={styles.credit}>+ ${transaction.credit}</td>
                    <td>{transaction.balance}</td>
                    </tr>
                )) : output.map(transaction => (
                    <tr key={transaction._id}>
                    {transaction.description.includes(input) ? <td className={styles.highlight}>transaction.description</td>: <td>transaction.description</td>} // Conditionally rendering component with styled class
                    <td>transaction.description.includes(input) ? transaction.description ? transaction.description</td> // Applying style directly 
                    <td>{transaction.date}</td>
                    <td className={styles.debit}>- ${transaction.debit}</td>
                    <td className={styles.credit}>+ ${transaction.credit}</td>
                    <td>{transaction.balance}</td>
                    </tr>
                ))}
            </tbody>
        </Table>

If this explanation is confusing, just know that the "input" mentioned refers to the e.target.value that I receive and the letters that I want to highlight as they are entered.

Thank you

Answer №1

{input.length 
< 1 ? displayTransactions.map(transaction => (
                   <tr key={transaction._id} className={**className**}>
                   <td>{transaction.description}</td>
                   <td>{transaction.date}</td>
                   <td className={styles.debit}>- ${transaction.debit}</td>
                   <td className={styles.credit}>+ ${transaction.credit}</td>
                   <td>{transaction.balance}</td>
                   </tr>
               ))

Utilizing the map() function here allows for generating unique code for each element in the array, allowing for direct targeting and applying a className to the topmost "tr" tag. This enables specific styling to be applied to individual elements within the table structure. Additionally, custom styles can be implemented by creating objects for styles and then using JavaScript DOM manipulation or conditional statements to apply these styles dynamically based on input values.

I previously used this approach successfully for a similar task, however, its effectiveness may vary depending on the specific requirements of the implementation!

Answer №2

If you want to dynamically include a class name in a td element depending on a search term, you can try the following code snippet:

<td className={transaction.description.includes(input) ? styles.highlight: ''}>
  {transaction.description}
</td>

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

Improving the quality of shadows in Three.js

I'm looking to create realistic shadows in my scene using a DirectionalLight to simulate sunlight. However, I'm struggling with the shadow quality settings - toggling between on/off, Low, Normal, and High: Setting parameters a and b within these ...

What causes bootstrap to fail on smaller screens?

While developing an app using Bootstrap, I encountered an issue where the app was not functioning properly on small screens. Everything worked perfectly on larger screens, such as a PC browser, but on a mobile browser, none of the tabs would open. When I t ...

Conceal Element in React if it is the Final Item

Is there a way to hide the TimelineConnector if it is on the last item? I am looking for some guidance on how to achieve this. Please take a look at my codesandbox below: CLICK HERE {timelines.lastIndexOf(index) !== 1 ? <TimelineConnector /> : &quo ...

Steer clear of directly accessing views in AngularJS using angular-ui-router

In my AngularJS App setup, I have the following configuration: angular .module('MyApp') .config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvi ...

What is the best way to test routing with Next JS using links?

As a newcomer to the NextJS environment and currently in the process of migrating an application from standard ReactJS, I am faced with a challenge regarding testing a link to another page. Can anyone provide some guidance on how I should refactor my test ...

Creating Header Images for Websites, like the way Facebook does

Exploring how to properly configure the header image on my website has been intriguing. The main issue is that when I view it on my laptop, which has a width resolution of around 1280px, the header image's width measures about 2000px. My goal is to h ...

Display issues with React styled components preventing proper rendering on the screen

Having issues with my style components displaying in a web application I'm developing using React and Ruby on Rails. Everything was working fine until I added a third style component, now even after removing it, nothing shows up on the screen after ru ...

Encountered an error when attempting to load the external module @babel/register during the

My React project runs smoothly on my VMware, but when I cloned the same app and executed the gulp command, I encountered an error during compilation: MacBook-Pro:Frontend1.0 apurvgandhwani$ gulp [18:42:31] Failed to load external module @babel/register ...

What is the best way to access an excel file using JavaScript and Protractor?

Is it possible to read an Excel file dynamically in JavaScript and iterate through cell values using row and column counts, without converting it into a JSON object? I have searched through several posts on Stack Overflow but have not found a solution yet. ...

There seems to be an issue with the zebra striping in the rich:datatable component when using the rowClasses

I'm attempting to give my table a "zebra" color pattern for the rows, but it seems like the rowClasses attribute isn't functioning properly (edit: I don't see any colors applied to the table at all). Here is how I defined the styles: <s ...

`How can a user be redirected in the Server component of Nextjs version 13?`

I'm a beginner with next js and looking for ways to redirect a user from a server component without relying on the "use client" method ...

What is the functionality of the ... operator in PHP?

During my daily office tasks, I often encounter various types of multidimensional arrays that sometimes need to be flattened into a single dimension for efficiency. My preferred method is usually using call_user_func_array with the array_merge parameter. ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Trouble accessing HTML file in web browser

I just finished creating a basic webpage called HelloWorld.html using HTML, JavaScript, and CSS. It runs smoothly when I open it from Eclipse IDE and view it through a browser. The functionality of the page is that it contains 5 buttons, each revealing th ...

Drop-down menu options failing to appear within the drop-down menu

I am facing an issue where the dropdown menu is visible but the items inside it are not appearing. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data ...

Utilizing an array to determine the highest common factor results in unexpected output (C++)

Regardless of the input, I consistently get the result 176 for my last output. My approach involves creating an Array (comfactors) and storing common factors in it. Then, I identify the highest number and place it in comfactors[0] before outputting ...

Puzzled by the CSS Box Model - There's a piece of the puzzle I

Check out my simplified fluid layout right here at this link. I've been trying to figure out why the alignment between the right column and the header above it seems off, even though there's no padding involved. Both have the same border styles, ...

Stopping the Game Loop in Windows Phone 8.1 with WinJS

Despite everything working smoothly, I am facing an issue with stopping the game loop when the Start button is pressed and the app is moved to the background. The event handler for suspend, app.oncheckpoint = function(args) {}, does not seem to fire for t ...

How to upload a file with JavaScript without using Ajax technology

Is it possible to upload a file using the input tag with type='file' and save it in my project folder without using ajax? Can JavaScript help me achieve this task? Below is the code snippet I am currently working on: function func3() { var ...

Tips for mastering web design techniques

As a budding Web Designer, I am eager to absorb the most efficient techniques utilized in the world of web design. Can anyone recommend some tutorials for mastering the creation of innovative websites using Photoshop, CSS, HTML, and more? ...