H
H
Hellas2017-01-30 16:47:46
React
Hellas, 2017-01-30 16:47:46

How to implement the selection of the found fragment?

For example, here - https://enkidevs.github.io/react-search-input/
It is necessary that the search phrase in the found elements be wrapped in a tag <span>{searchTerm}</span>, for example:
4f727ebacde04f569a2e5a0055d0ba9b.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2017-01-30
@Hellas

Working example (jsfiddle)
The main logic is in the SearchResults component:

class SearchResults  extends React.PureComponent {

  render() {
  const { target, results } = this.props

  	return (
    	<div className="SearchResults">
    	  {_
        	.chain(results)
        	.map(word => word.split(target))
                .map(parts => _.reduce(
              	  parts,
                  (res, part) => res.length > 0
                   ? [ ...res, <span className="highlight">{target}</span>, part ]
                   : [ part ]
          	  ,
                  []
        	))
                .map(word => <span className="word">{word}</span>)
                .value()
          }
    	</div>
    )
  }
}

We split the words into an array (example 'Mathieu'.split('th') => ['Ma', 'eu'])
Then we collect them back, while to the left of each "piece" of the word we insert our separator (what you need highlight with color), wrapping it in a span along the way:
.map(parts => _.reduce(
  parts,
  (res, part) => res.length > 0
    ? [ ...res, <span className="highlight">{target}</span>, part ]
    : [ part ]
  ,
  []
))

Well, then we wrap the resulting array in a span, which will be a container for the word (search result):
.map(word => <span className="word">{word}</span>)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question