Sorry, the provided text is already unique as it is an error message

  • I'm currently using the react-highlight-words package to highlight text inputted into a textbox
  • After checking out the react-highlight-words documentation, I noticed that they are using searchWords as an array. https://www.npmjs.com/package/react-highlight-words
  • However, I encountered an error when passing it an array with let searchBarText = [];, saying searchWords.filter is not a function.
  • Could you help me figure out how to resolve this issue so I can address similar problems on my own in the future?
  • Below are links to my sandbox and code snippet for reference.

https://codesandbox.io/s/00nm6k8orp

class SearchBar extends React.Component {
  constructor() {
    super();
    this.state = {
      // testHighlight: {}
      testHighlight: []
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    console.log(e.target.value); // your search bar text
    let object = document.getElementById("myDiv");
    console.log(object.textContent); // your div text

    // now that you have the two strings you can do your search in your favorite way, for example:
    let searchBarText = [];
    searchBarText = e.target.value;
    console.log("searchBarText --->", searchBarText);

    let divText = object.textContent;
    console.log("divText --->", divText);

    if (divText.includes(searchBarText)) {
      console.log("the div text contains your search text");
    } else {
      console.log("the div text doesn't contain search text");
    }

    // this.setState({ testHighlight: response.data });

    this.setState({ testHighlight: searchBarText });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          className="input"
          onChange={this.handleChange}
          placeholder="Search..."
          // highlightText={this.handleChange}
          testHighlight={this.state.testHighlight}
        />

        <HighlighterImplementation testHighlight={this.state.testHighlight} />
      </div>
    );
  }
}

Answer №1

When working on the SearchBar.js file, make sure to update the testHighlight by assigning it a string:

this.setState({ testHighlight: searchBarText });

Perhaps you intended to do the following instead:

this.setState({ testHighlight: [searchBarText] });

Alternatively, if you want to incorporate it into the existing array:

this.setState({ testHighlight: [...this.state.testHighlight, searchBarText] });

Answer №2

Ensure that your 'testHighlight' state is saved as an array, not a string, to work with the 'HighlighterImplementation' component.

To convert the string to an array, use the split() method when setting the state as a prop.

Although you have set the initial state of searchBarText, ensure it remains a string in the onChange event handling.

this.setState({ testHighlight: searchBarText });

To correctly pass the state as an array:

<HighlighterImplementation testHighlight={this.state.testHighlight.split('')} />

Make sure to initialize the state as a string for this method to work effectively.

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

Utilizing CSS to Rearrange Columns Depending on Screen Size

Check out the progress on this page: If you scroll to the bottom, you'll find a list of links - displayed in 4 columns in the regular view. When you resize the screen, they shift into a single column. I want them to show as a single column on an iPh ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

"Enhance Your Video Experience with a Personalized Play Button

Is it possible to customize the play icon for an embedded YouTube video? I came across a post discussing this topic: Can I change the play icon of embedded youtube videos? However, when trying to use something transparent as the new play button, the origin ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

Passing data back from an asynchronous function to its parent function in Node.js

Exploring the world of asynchronous programming is a new adventure for me as I delve into implementing Twilio video calls through Node.js. I've been grappling with calling a server-side function that in turn invokes another asynchronous function retu ...

Different ways to customize the color of a box component in Material UI

I'm brand new to web development and I'm having trouble changing the box color using Material-UI. The color I want is success.main, but so far I'm only getting the default primary blue. I've tried adjusting every box component with no l ...

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

Encountering a talebook mishap: the function fn.apply is not recognized

Currently, I'm in the process of refactoring a React webapp from CRA to utilizing Vite and encountering some hurdles with Storybook. The Storybook's interface opens up as expected, displaying a list of stories on the left panel. However, when sel ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Using the responsive design mode may not accurately reflect the mobile user experience

Recently, I've been working on designing a new cover for my book using HTML and CSS. After completing the design, I previewed it in Responsive Design mode on both Firefox and Google Chrome. However, when I tried to view the website on my phone (a Gala ...

Version Control in Ionic React Projects

I am working on an Ionic React Project that was created using Ionic Cli ionic start with the blank template. How do I go about setting the project's version that appears in the package.json file? Is it enough to just update the version there, or sho ...

Is the code generated by Webflow.com functional and practical?

Recently, I have discovered the wonders of www.webflow.com for creating an admin layout. It excels in generating a flexbox layout based on my PSD design without requiring me to manually code with Gulp. My plan is to further simplify the process by breaki ...

Continuous scroll notification within the fixed menu until reaching the bottom

I'm looking to achieve a scrolling notification message that stays fixed at the bottom of a top-fixed menu while the body content continues to scroll normally. Here's an example in this fiddle: HTML: <div class="menu-fixed">I am a fixed me ...

When attempting to implement styled-components in Next.js, there is an issue with the node module in React.js causing an error

I am trying to incorporate styled-components in my next.js react project. This is the approach I am taking: import styled from 'styled-components'; export const MainTitleContainer = styled.div` text-align:right; margin:3rem 0; paddin ...

"Encountering an issue with Material UI where the Theme Style typography is not

Trying to update typography in the theme using Material UI but facing issues with object changes not working. The palette, however, is functioning correctly. Attempts were made to modify H3 styles and default font size but without success. On the contrar ...