最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React search bar searching text in Div in a component - Stack Overflow

programmeradmin3浏览0评论

I am trying to make a search bar to search a text in a ponent, may i know if it is possible to do?

class App extends React.Component {
    render() {
       return (
           /**search the text inside this DIV**/
          <div> this is a dog. </div>
       )
    }
}  

Thanks:)

I am trying to make a search bar to search a text in a ponent, may i know if it is possible to do?

class App extends React.Component {
    render() {
       return (
           /**search the text inside this DIV**/
          <div> this is a dog. </div>
       )
    }
}  

Thanks:)

Share Improve this question edited Nov 28, 2018 at 0:53 reisdev 3,4032 gold badges20 silver badges41 bronze badges asked Nov 26, 2018 at 20:39 fong leefong lee 891 gold badge2 silver badges7 bronze badges 1
  • you can select all div using document.querySelectorAll and check text inside of div – fiddlest Commented Nov 26, 2018 at 21:09
Add a ment  | 

3 Answers 3

Reset to default 2

Here's the way I would implement it

class App extends React.Component {

    constructor() {
        super();
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {
        console.log(e.target.value); // your search bar text
        let object = this.refs.Progress1; // get your div element using refs
        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 = e.target.value;
        let divText = object.textContent;
        if (divText.includes(searchBarText)) {
            console.log("the div text contains your search text");
        } else {
            console.log("the div text doesn't contain search text");
        }
    }

    render() {
        return (
            <div>
                <input type="text" className="input" onChange={this.handleChange} placeholder="Search..." />
                <div ref="Progress1">
                    this is a dog. ...
                </div>
            </div>
        );
    }
}

Update: if the div and the search bar are in two different React ponents without parent/child relation, I would implement it as follows:

Class A having the div

class A extends React.Component {

    constructor() {
        super();
    }

    render() {
        return (
            <div>
                <div id="myDiv">
                    this is a dog. ...
                </div>
            </div>
        );
    }
}

class B having the search bar

class B extends React.Component {

    constructor() {
        super();
        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 = e.target.value;
        let divText = object.textContent;
        if (divText.includes(searchBarText)) {
            console.log("the div text contains your search text");
        } else {
            console.log("the div text doesn't contain search text");
        }
    }

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

If there is a parent/child relation between the two classes/ponents you should rely on props passing between parent and child, see this question for an example: How to get refs from another ponent in React JS

Is the text inside of your ponent pure markup or controlled within the ponent's state?

If it's pure markup then you'll have to interact with the dom -- something you can do using refs:

https://reactjs/docs/refs-and-the-dom.html

In either case, whether it's controlled ponent or markup, you'll have to obtain that inner text somehow and pass it to an event handler attached to your search bar. From there the question is the best way to search within text. I'll leave that up to you (Regex, etc...)

If anyone searching how to do it in React Hook. This is for you:

import React, { useState, useRef } from "react";

export default function App() {
  const [text, setText] = useState("");
  const [isFound, setFound] = useState(false);
  const paragraphEl = useRef(null);

  const handleInput = (e) => {
    setText(e.target.value);
    const paragraphText = paragraphEl.current.textContent;
    if (e.target.value !== "" && paragraphText.includes(e.target.value)) {
      setFound(true);
    } else {
      setFound(false);
    }
  };

  return (
    <div>
      <h1>Search text</h1>
      <input
        type="text"
        placeholder="Type here"
        value={text}
        onChange={handleInput}
      />
      <p ref={paragraphEl}>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
        veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
        modo consequat. Duis aute irure dolor in reprehenderit in voluptate
        velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.
      </p>
      {isFound && <p style={{ color: "green" }}>We found it</p>}
    </div>
  );
}
发布评论

评论列表(0)

  1. 暂无评论