React - show the last array and create const for reusability

0 votes
17 views
added Feb 1 in React by lcjr First Warrant Officer (10,930 points)

Here's the constant:

const latestKeyedText = cookies.searchHistory.length > 0 && (
    <div key={cookies.searchHistory.length - 1}>
      {`${cookies.searchHistory[cookies.searchHistory.length - 1]}`}
    </div>
  );

 

How to use it:

<div> Searching for: {latestKeyedText}</div>

 

Here's the full code:

import React, { useState, useEffect } from 'react';
import { css, jsx } from '@emotion/react';
import { useCookies } from 'react-cookie';

const MainComp = () => {
  const [searchText, setSearchText] = useState('');
  const [cookies, setCookie] = useCookies(['searchHistory']);

  // Ensure that searchHistory is initialized as an array
  useEffect(() => {
    if (!cookies.searchHistory) {
      setCookie('searchHistory', []);
    }
  }, [cookies.searchHistory, setCookie]);

  const handleInputChange = e => {
    const inputText = e.target.value;
    if (inputText.length <= 100) {
      setSearchText(inputText);
    }
  };

  const handleSearch = () => {
    // Store the searched text in cookies
    setCookie('searchHistory', [...cookies.searchHistory, searchText], {
      path: '/',
    });
    setSearchText('');
  };

  const latestKeyedText = cookies.searchHistory.length > 0 && (
    <div key={cookies.searchHistory.length - 1}>
      {`${cookies.searchHistory[cookies.searchHistory.length - 1]}`}
    </div>
  );

  return (
    <div>
      <input
        type="text"
        value={searchText}
        onChange={handleInputChange}
        placeholder="Type here..."
      />
      <p>
        Character Count:
        {searchText.length}
        /100
      </p>
      <button className="SendButton" onClick={handleSearch}>
        Send
      </button> 
        <div 
          className="searchText"
          css={css`
            background: #eee;
          `}
        >
        <div className="searchText">{latestKeyedText}</div>
      </div>

      <div> Searching for: {latestKeyedText}</div>
      <div>Generating answers for you…</div>
    </div>
  );
};

export default MainComp;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...