React - dynamically toggle class in react

0 votes
12 views
added Jan 29 in React by lcjr First Warrant Officer (10,930 points)

To make the input field expand when the button is minimized after clicking, you can dynamically toggle a class on the parent container and adjust the styles accordingly. Please observe this line:

const [isExpanded, setExpanded] = useState(false);

and,

<div className={`right_buddySearch ${isExpanded ? 'expanded' : ''}`}>

Here's a simple example using React and CSS:

 

import React, { useState } from 'react';
import './YourStyles.css'; // Import your styles file

const YourComponent = () => {
  const [searchText, setSearchText] = useState('');
  const [isExpanded, setExpanded] = useState(false);

  const handleInputChange = (e) => {
    setSearchText(e.target.value);
  };

  const handleInputFocus = () => {
    setExpanded(true);
  };

  const handleInputBlur = () => {
    setExpanded(false);
  };

  const handleSearch = () => {
    // Your search logic here
  };

  return (
    <div className={`right_buddySearch ${isExpanded ? 'expanded' : ''}`}>
      <div className="buddySearch_container">
        <input
          type="text"
          className="buddySearch_input"
          placeholder="Ask us anything..."
          value={searchText}
          onChange={handleInputChange}
          onFocus={handleInputFocus}
          onBlur={handleInputBlur}
        />
        <div className="char-counter">
          {searchText.length}/{maxCharacters}
        </div>
        <button className="buddySearch_send" onClick={handleSearch}>
          <img src="/assets/icons/send_24.png" alt="Send" />
          {/* 
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...