Search code examples
javascriptcssreactjsalgorithmstyled-components

Input field focus state in react not working with the given style


I have an input field in my react project to display a separate component when it's in a hover state. I have a separate component called [Focus Style] from the Actual component but all I'm doing is not working. The focus state should work with the first input field Kindly assist me. My code below.

Main Componenet

import React, { useState, useEffect } from "react";
 import stays from "./Components/stays.json";
// import styled, {css} from "styled-components";
import FocusStyle from "../src/Components/FocusStyle";

export default function SearchGuest() {
  const [guest, setGuest] = useState("");
  const [location, setLocation] = useState("");
  const [Data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState(Data);
  const [focus, setFocus] = useState("false");

  const onFocusChange = () => {
    setFocus("true");
    console.log("focused");
  };

  

  useEffect(() => {
    setData(stays);
    setFilteredData(stays);
  }, []);

  const handleSearch = (event) => {
    event.preventDefault();
    
  };

  return (
    <div>
      <form action="" >
        <input
          onFocus={onFocusChange}
          type="text"
          name="guest"
          id=""
          // value={guest}
          placeholder="text"
          onChange={handleSearch}
          style={focus ? { border: "1px solid yellow" } :  <FocusStyle/>  }
        />
        <input
          type="number"
          name="location"
          id=""
          // value={location}
          placeholder="number"
          onChange={handleSearch}
        />
        <button value="submit" >Search</button>
      </form>

      {console.log(filteredData)}
    </div>
  );
}

FocusStyle Component

import React from 'react'

export default function FocusStyle() {
  return (
    <div>
      <h2 style={{marginTop: "90px", color: 'pink'}}>Focus Componenet</h2>

      <div className="modal">
      <div className="adult">
    <span>Adult</span>
    <button>-</button><span>0</span><button>+</button>
    </div>

      <div className="children">
       <span>Children</span>
      <button>-</button><span>0</span><button>+</button>
      </div>


      </div>
    </div>
  )
}



Solution

  • if so then you can do this

    {focus ? <input
          onFocus={onFocusChange}
          type="text"
          name="guest"
          id=""
          // value={guest}
          placeholder="text"
          onChange={handleSearch}
          style={{ border: "1px solid yellow" }}
        />: 
       <FocusStyle/>
    }