reactRookie
reactRookie

Reputation: 189

onClick in reactjs not showing items

I have to show a list of defaultValues in the search list and when I click on any of those item then it should take me to that item's component but it's not going anywhere. It's only happening with the defaultValues because as soon as I start typing, then if I click on any search result then it takes me to the desired component. what is wrong with my code?

here's the code

const [search, setSearch] = useState("");
const [showDefaultValues, setShowDefaultValues] = useState(false);
const [defaultValues] = useState({
    Mumbai: true
  }); 

 {!search.length && showDefaultValues ? (
            <div className="result-box">
              {data
                .filter((item, idx) => defaultValues[item.district])
                .map((dist, idx) => (
                  <div
                    key={idx}
                    className="search-result"
                    onClick={() => {
                      
                      onResultClick(dist.district);
                    }}
                  >
                    {highlightedText(dist.district, search)}
                    
                  </div>
                ))}
            </div>
          ) : null}

Upvotes: 0

Views: 83

Answers (2)

Thirumani guhan
Thirumani guhan

Reputation: 398

Just change the codes at components/search/search.js line 39 to 49

<input
   placeholder="Search for a District..."
   type="text"
   className="search-input"
   value={search}
   onChange={onSearchInputChange}
   onFocus={() => {
      toggleDefaultValues(true);
   }}
   onBlur={onBlurInput}
/>

To

<input
   placeholder="Search for a District..."
   type="text"
   className="search-input"
   value={search}
   onChange={onSearchInputChange}
   onFocus={() => {
      toggleDefaultValues(true);
   }}
/>

Or simply remove line 48

To compensate this, you can add below inside your useEffect (similar to componentDidMount)

document.addEventListener("mousedown", handleInputClickOutside);

add function handleInputClickOutside to set the state to false/hide

Upvotes: 1

Manu Sharma
Manu Sharma

Reputation: 764

You forgot to implement the onClick logic on the default search result items and that's why the search results work fine, while the default search items do not.

Check this link to the working codesandbox.

All i did was invoke the same onResultClick function onClick of 'District' component.

<div
        className="dist"
        onClick={() => {
          this.props.onResultClick(item.district);
        }}
      >
...
</div>

Hope this solves your problem.

Upvotes: 1

Related Questions