I have found a few closely related questions, but not so close enough. I am trying to style only the searched part of the search result. For example, if the query is "Thi", I want the result to appear as Things fall apart. My problem is it renders [object Object] right inside the browser. How do I make it render the desired text and so I can freely style it with CSS3? The other problem I have is a warning in the browser console that
index.js:1 Warning: Each child in a list should have a unique "key" prop.
Code below:
import React, { Fragment } from "react";
import CancelIcon from "@material-ui/icons/Cancel";
import CallMadeIcon from "@material-ui/icons/CallMade";
export default function SearchBar(props) {
return (
<Fragment>
<div className="search">
<div
className="search-input-container"
ref={props.searchInputContainerRef}
>
<label htmlFor="search-input"></label>
<input
type="text"
id="search-input"
placeholder={props.placeholder}
onChange={props.handleSetSearchTerm}
value={props.searchTerm}
ref={props.searchInputRef}
onFocus={props.blurAllOnSearch}
onBlur={props.blurAllOnSearch}
onKeyUp={props.handleFilter}
/>
{props.searchTerm === "" ? (
<button
ref={props.searchIconVectorRef}
type="button"
className="search-icon-btn"
onClick={props.focusSearchInput}
></button>
) : (
<CancelIcon
className="clear-btn"
type="button"
onClick={props.clearSearchInput}
/>
)}
<button className="go-search-btn">Go</button>
</div>
{props.searchResults.length !== 0 && (
<div className="search-results">
{props.searchResults.slice(0, 15).map((value, key) => {
const boldResultPart = (result, query) => {
let re = new RegExp(query, "ig");
return result
.replace(/- /g, "")
.replace(/\./g, "")
.replace(re, <span className="boldFont"> ${query} </span>); // <-- *My problem is this span renders as [object Object] in the browser*
};
let bolded = boldResultPart(value.title, props.searchTerm);
return (
<li className="data-item">
<a
className="result"
href={value.link}
target="_blank"
rel="noreferrer"
>
{bolded}
</a>
<CallMadeIcon className="call-made-icon" />
</li>
);
})}
</div>
)}
</div>
</Fragment>
);
}