All I want here is when I press the search button in Hero.jsx , I set a value to the guest constant in Hotelcards.jsx , any solutions ?
the guest value that I wanna set is on this file.
Hotelcards.jsx
import { Link } from "react-router-dom"; import React,{useState,useEffect} from 'react'; import styles from '../styles/HotelListCards/HotelCards.module.css'; import {Checkkin as checkkin} from "./Hero"; import {Checkkout as checkkout} from "./Hero"; import {rowss as rows } from "./Hero"; import {notavailableat as notavailableat } from "./Hero"; import {prices as prices } from "./Hero"; const HotelCards = ({ idroom , title, status = true, price, img }) => { const [guests, setGuest] = useState('') const [qty, setTitle] = useState('') var total_price = 0; if(prices.length!==0){ for (var i=0;i<prices.length-1;i++){ total_price+=parseFloat(prices[i]); } } };
And the button that will trigger the event of changing the value is on this file. Hero.jsx
import React, {useEffect, useState, useCallback} from 'react'; import styled from 'styled-components'; import homeImage from '../assets/booking-bg.jpg'; import styles from '../styles/HotelListCards/HotelCards.module.css'; import {differenceInDays, format} from "date-fns"; var Checkkin = 0; var Checkkout= 1; let notavailableat=""; let rowss=[]; let prices =[]; export {Checkkin,Checkkout,rowss,notavailableat,prices}; export default function Hero() { const [availdata, setavailData] = useState([]); const [isLoading, setIsLoading] = useState(false); }
<div className="search"> <button >Search</button> </div>
Advertisement
Answer
So the solution was wrapping both siblings in a parent component and handle the state inside the parent component. Then you easily can share the state between any siblings that you want and use the state inside the child components. :
in the parent component :
function App() { const [selectedMode, setSelectedMode] = useState('open') . . . <> <NewNavbar /> <Hero setSelectedMode={setSelectedMode} /> <Services /> <Options selectedMode={selectedMode}/> <ScrollToTop /> <Footer /> {/* <PaymentSummaryFinal1 />*/} </>
in the first sibling Hero:
export default function Hero({setSelectedMode}) { const onButtonClick=(mode)=>{ setSelectedMode(mode) } . . . <button onClick={()=>onButtonClick('closed')} >Search</button>
and on the other sibling Options.jsx
export default function Options({selectedMode}) { . . . return ( <div className={`${styles.containers}`}> <div> <HotelCards mode={selectedMode} // pass it to the child of this sibling /> </div> )} </div> ); }
Thanks to Chad S in the comments.