React - useState hook for managing state between 2 components in a page

0 votes
74 views
added Jan 25 in React by lcjr First Warrant Officer (11,930 points)

This example uses the useState hook for managing state and the react-cookie library for handling cookies.

MainComp Component

// Install react-cookie using: npm install react-cookie

// MainComp.jsx
import React, { useState } from 'react';
import { useCookies } from 'react-cookie';

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

  const handleSend = () => {
    if (searchText.trim() !== '') {
      onSend(searchText);
      setSearchText('');
    }
  };

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

  return (
    <div>
      <input type="text" value={searchText} onChange={handleChange} placeholder="Type here..." />
      <button onClick={handleSend}>Send</button>
      <p>Character count: {searchText.length}/100</p>
      <p>Search History:</p>
      <ul>
        {cookies.searchHistory && cookies.searchHistory.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

export default MainComp;

 

SideCom component

// SideCom.jsx
import React from 'react';

const SideCom = ({ searchHistory }) => {
  return (
    <div>
      <h2>Search History</h2>
      <ul>
        {searchHistory.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

export default SideCom;

 

Page that importing and bind the search field from MainComp to history list in SideCom

// App.jsx, the page

import React, { useState } from 'react';
import MainComp from './MainComp';
import SideCom from './SideCom';

const App = () => {
  const [searchHistory, setSearchHistory] = useState([]);

  const handleSend = (searchText) => {
    setSearchHistory((prevHistory) => [...prevHistory, searchText]);
  };

  return (
    <div>
      <MainComp onSend={handleSend} />
      <SideCom searchHistory={searchHistory} />
    </div>
  );
};

export default App;

 

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