Pass information from an input to another component in another file - reactjs

I'm having a problem, it's been a few days, I'm studying about React and Typescript and I'm developing a temperature application, I'm stopped in a part, where I want the user to click on the submit form, the information that was typed in the input is passed to another component.
Follow my two codes below
CityWeatherSearch.tsx
import { MagnifyingGlass } from 'phosphor-react'
import { FormEvent, useCallback, useRef, useState } from 'react';
import * as Styled from './style'
export function CityWeatherSearch(){
const inputRef = useRef<HTMLInputElement>(null);
const [city,setCity] = useState('');
function handleClick(event:FormEvent) {
event.preventDefault();
const inputCity = inputRef?.current?.value;
console.log({
inputCity, city
});
}
return(
<>
<Styled.BoxSearchCity>
<div className="headerSearch">
<form>
<input type="text" placeholder='Procurar Cidade...' ref={inputRef} onChange={
event => setCity(event.target.value)} />
<button type="submit" onClick={handleClick}>
<MagnifyingGlass/>
</button>
</form>
</div>
<div className="bodySearch">
{city}
</div>
</Styled.BoxSearchCity>
</>
)
}
MainWeatherLive.tsx
import {Clock} from 'phosphor-react'
import { useFetch } from '../../GetData/useFetch'
import * as Styled from './style'
type DataWeather = {
name: string,
condition:{
text:string,
icon:string
},
temp_c:number,
hour:[{
temp_c:number,
time:string,
condition:{
text:string,
icon:string
}
}]
}
export function MainWeatherLive(){
const {dataLocation: dataWeatherApi, isFetching, dataCurrent:dataCurrentApi, dataForecast:forecastApi}
= useFetch<DataWeather>('/v1/forecast.json?key=aff6fe0e7f5d4f3fa0611008221406&q=Guarulhos?days=1&aqi=no&alerts=no');
return(
<>
<Styled.HeaderBox>
<h6>Weather Now</h6>
</Styled.HeaderBox>
<Styled.Container>
{isFetching &&
<p>Carregando...</p>
}
<div className="mainInformation">
<div className="temperatura">
<span>{dataCurrentApi?.temp_c}º</span>
</div>
<div>
A cidade é {cityName}
</div>
<div className="boxCidade">
<div className="cidade">
<span>{dataWeatherApi?.name}</span>
</div>
<div className="tempoHoras">
<span>
{new Date().toLocaleTimeString('pt-BR',{hour12:false, hour:'numeric',minute:'numeric'})} - {new Date().toLocaleDateString()}
</span>
</div>
</div>
<div className="iconeTem">
<img src={dataCurrentApi?.condition.icon} alt={dataCurrentApi?.condition.text} />
</div>
</div>
<div className="footerBox">
<div className="headerFooter">
<Clock/>
<span>Horários</span>
</div>
<div className="listaHorarios">
<ul className="boxTT">
{
forecastApi?.hour?.map(weatherA =>{
const hourTemp = weatherA.time.split(" ")[1].replace(":00","");
const hourTempNumber:number = +hourTemp;
const hourNow = new Date().getHours();
return(
<>
{
hourTempNumber == hourNow &&
<li>
<div className="titulo" key={weatherA.temp_c}>
<span>{hourTempNumber}</span>
</div>
<div className="temperatura">
<img src={weatherA.condition.icon} alt={weatherA.condition.text} />
<span>{dataCurrentApi?.temp_c}º</span>
</div>
</li>
}
{
hourTempNumber > hourNow &&
<li>
<div className="titulo" key={weatherA.temp_c}>
<span>{hourTempNumber}</span>
</div>
<div className="temperatura">
<img src={weatherA.condition.icon} alt={weatherA.condition.text} />
<span>{weatherA.temp_c}º</span>
</div>
</li>
}
</>
)
})
}
</ul>
</div>
</div>
</Styled.Container>
</>
)
}
Weather.tsx
import { CityWeatherSearch } from "./WeatherC/CityWeatherSearch";
import { MainWeatherLive } from "./WeatherC/MainWeatherLive";
import { WeatherDetails } from "./WeatherC/WeatherDetails";
import coldImage from '../assets/cold.jpg'
import sunImage from '../assets/sun.jpg'
import rainImage from '../assets/rain.jpg'
import nightVideo from '../assets/night.mp4'
import night from '../assets/night.jpg'
export const TypesWeather = {
NIGHT:{
video:{
source: nightVideo
},
image:{
source: night
}
},
OVERCAST:{
video:{
source: nightVideo
},
image:{
source: night
}
},
COLD:{
image:{
source: coldImage,
title: 'Frio'
}
},
SUN:{
image:{
source: sunImage,
title: 'Verão'
}
},
RAIN:{
image:{
source: rainImage,
title: 'Chuva'
}
},
};
export type TypesWeatherV2 = keyof typeof TypesWeather;
export function Weather(){
return (
<>
<div className="globalSite" style={{background:`linear-gradient(to bottom,rgba(0,0,0,.85) 0,rgba(0,0,0,.85) 100%),url(${TypesWeather.RAIN.image.source})`}}>
</div>
<div className="boxAllWeather">
<div className="backgroundWeather" style={{backgroundImage:`url(${TypesWeather.RAIN.image.source})`}}></div>
<div className="boxAllInff">
<div className="mainWeather">
<MainWeatherLive />
</div>
<div className="otherInfoWeather">
<CityWeatherSearch />
<WeatherDetails />
</div>
</div>
</div>
</>
)
}
I want to pass the city typed in CityWeatherSearch.tsx to MainWeatherLive.tsx. Where is the space 'A cidade é {cityName}' reserved, I've tried everything, but I haven't been able to, could you help me?

You can do this in several ways:
parent -> child : use props
child -> parent : use callback/event emitter
no direct relationship : consider using state management tool like
redux

Just lift your state uo to the parent component and pass if to the cild components as props:
function WeatherPage() {
const [city,setCity] = useState('');
return (
<>
<CityWeatherSearch city={city} setCity={setCity}/>
//...
<MainWeatherLive city={city}/>
//...
</>
)
}
function CityWeatherSearch({city, setCity}) {
// your code here, only without const [city, setCity] useState()
}
function MainWeatherLive({city}) {
// your code here, now you can access city
}
If your two components don't have a direct common parent and you don't want to pass down city and setCity through a deep component hierarchy, think about using useContext to share state within your application.

Related

React change css style of a div in another component by button clicking in another component

on my Project I have a banner on top of my site with 2 buttons. when I click the button profile I want it to change the css style of a div in another component.
this is my code for the banner:
import Profile from "./Profile";
function Banner() {
const invis=false;
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={Profile.changeStyle}>Profile</button>
</span>
</div>
);
}
export default Banner;
this is my code for the div in the other component:
import "../index.css";
import React, { useState } from "react";
const Profile = () => {
const [style, setStyle] = useState("profile-hidden");
const changeStyle = () => {
console.log("you just clicked");
setStyle("profile-displayed");
};
return (
<div>
<div className={style}> hellllo</div>
</div>
);
};
export default Profile;
I can only find information about this with parent-child components.
They said I should use a usestate import but I can't seem to get it working. what's the proper way to do this?
All you need is lift your state to parent component, if you have a long trip to your common ancestor you can try to use a context. Attached a working example. Hope it helps!
const Banner = ({ onClickHandler }) => {
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={() => onClickHandler()}>Profile</button>
</span>
</div>
)}
const Profile = ({ style }) => {
return (
<div>
<div className={style}>I'm your profile :)</div>
</div>
);
};
const App = () => {
// We lift the state
const [style, setStyle] = React.useState("profile-hidden");
const profileHandler = () => {
setStyle(style === 'profile-hidden'
? 'profile-displayed'
: 'profile-hidden')
}
return(
<div>
<Banner onClickHandler={profileHandler} />
<Profile style={style} />
</div>
)
}
// Render
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
.profile-hidden {
display: none;
}
.profile-displayed {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>
You cannot use this syntax for React Components COMPONENT.method
, in your case onClick={Profile.changeStyle} !
Instead you should make Banner parent component and use Profile component as child inside it or vise versa !
then You should pass the state style as props so then you will be able to use its value.
your code should look like this :
function Banner() {
const [style, setStyle] = useState("profile-hidden");
const changeStyle = () => {
console.log("you just clicked");
setStyle("profile-displayed");
};
return (
<div className="banner">
<span className="bannerbtnsettings">
<button className="btnbannersettings">Settings</button>
</span>
<span className="bannerbtnprofile">
<button className="btnbannerprofile" onClick={changeStyle}>Profile</button>
</span>
<Profile style={style} />
</div>
);
}
export default Banner;
and your Profile component :
const Profile = (props) => {
return (
<div>
<div className={props.style}> hellllo</div>
</div>
)
}

How to render input information and send it to my api's fetch?

I'm having a problem, which is to bring the weather information of a city where the user typed in the input, to my component.
I managed to make it so that when the user typed the city or country, it was already entered as a parameter in my api, but the weather information only appears when I CTRL+S my tsx file.
The same follows in the codes and images below
CityWeatherSearch.tsx
import { MagnifyingGlass } from 'phosphor-react'
import { FormEvent, useRef, useState } from 'react';
import * as Styled from './style'
interface CityPropsP{
city:string,
setCity: typeof useState
}
export function CityWeatherSearch({city,setCity}:CityPropsP){
const inputRef = useRef<HTMLInputElement>(null);
function handleClick(event:FormEvent) {
event.preventDefault();
const inputCity = inputRef?.current?.value;
setCity(inputCity)
}
return(
<>
<Styled.BoxSearchCity>
<div className="headerSearch">
<form onSubmit={handleClick}>
<input type="text" placeholder='Procurar Cidade...' ref={inputRef} />
<button type="submit">
<MagnifyingGlass/>
</button>
</form>
</div>
<div className="bodySearch">
</div>
</Styled.BoxSearchCity>
</>
)
}
MainWeatherLive.tsx
import {Clock} from 'phosphor-react'
import { useState } from 'react'
import { useFetch } from '../../GetData/useFetch'
import * as Styled from './style'
type DataWeather = {
name: string,
condition:{
text:string,
icon:string
},
temp_c:number,
hour:[{
temp_c:number,
time:string,
condition:{
text:string,
icon:string
}
}]
}
interface CityPropsMain{
city:string,
}
export function MainWeatherLive({city}: CityPropsMain){
const {dataCurrent:dataCurrentApi, dataForecast:forecastApi}
= useFetch<DataWeather>(`/v1/forecast.json?key=aff6fe0e7f5d4f3fa0611008221406&q=${city}?days=1&aqi=no&alerts=no`);
console.log(city)
return(
<>
<Styled.HeaderBox>
<h6>Weather Now</h6>
</Styled.HeaderBox>
<Styled.Container>
{city == '' &&
<p>Carregando...</p>
}
<div className="mainInformation">
<div className="temperatura">
<span>{dataCurrentApi?.temp_c}º</span>
</div>
<div>
</div>
<div className="boxCidade">
<div className="cidade">
<span>{city}</span>
</div>
<div className="tempoHoras">
<span>
{new Date().toLocaleTimeString('pt-BR',{hour12:false, hour:'numeric',minute:'numeric'})} - {new Date().toLocaleDateString()}
</span>
</div>
</div>
<div className="iconeTem">
<img src={dataCurrentApi?.condition.icon} alt={dataCurrentApi?.condition.text} />
</div>
</div>
<div className="footerBox">
<div className="headerFooter">
<Clock/>
<span>Horários</span>
</div>
<div className="listaHorarios">
<ul className="boxTT">
{
forecastApi?.hour?.map(weatherA =>{
const hourTemp = weatherA.time.split(" ")[1].replace(":00","");
const hourTempNumber:number = +hourTemp;
const hourNow = new Date().getHours();
return(
<>
{
hourTempNumber == hourNow &&
<li>
<div className="titulo" key={weatherA.temp_c}>
<span>{hourTempNumber}</span>
</div>
<div className="temperatura">
<img src={weatherA.condition.icon} alt={weatherA.condition.text} />
<span>{dataCurrentApi?.temp_c}º</span>
</div>
</li>
}
{
hourTempNumber > hourNow &&
<li>
<div className="titulo" key={weatherA.temp_c}>
<span>{hourTempNumber}</span>
</div>
<div className="temperatura">
<img src={weatherA.condition.icon} alt={weatherA.condition.text} />
<span>{weatherA.temp_c}º</span>
</div>
</li>
}
</>
)
})
}
</ul>
</div>
</div>
</Styled.Container>
</>
)
}
Weather.tsx
import { CityWeatherSearch } from "./WeatherC/CityWeatherSearch";
import { MainWeatherLive } from "./WeatherC/MainWeatherLive";
import { WeatherDetails } from "./WeatherC/WeatherDetails";
import coldImage from '../assets/cold.jpg'
import sunImage from '../assets/sun.jpg'
import rainImage from '../assets/rain.jpg'
import nightVideo from '../assets/night.mp4'
import night from '../assets/night.jpg'
import { useState } from "react";
export const TypesWeather = {
NIGHT:{
video:{
source: nightVideo
},
image:{
source: night
}
},
OVERCAST:{
video:{
source: nightVideo
},
image:{
source: night
}
},
COLD:{
image:{
source: coldImage,
title: 'Frio'
}
},
SUN:{
image:{
source: sunImage,
title: 'Verão'
}
},
RAIN:{
image:{
source: rainImage,
title: 'Chuva'
}
},
};
export type TypesWeatherV2 = keyof typeof TypesWeather;
export function Weather(){
const [city,setCity] = useState('');
return (
<>
<div className="globalSite" style={{background:`linear-gradient(to bottom,rgba(0,0,0,.85) 0,rgba(0,0,0,.85) 100%),url(${TypesWeather.RAIN.image.source})`}}>
</div>
<div className="boxAllWeather">
<div className="backgroundWeather" style={{backgroundImage:`url(${TypesWeather.RAIN.image.source})`}}></div>
<div className="boxAllInff">
<div className="mainWeather">
<MainWeatherLive city={city} />
</div>
<div className="otherInfoWeather">
<CityWeatherSearch city={city} setCity={setCity}/>
<WeatherDetails city={city} setCity={setCity} />
</div>
</div>
</div>
</>
)
}
When I search for a city or state and click search, the name appears normally, but without the updated information
When I save the component responsible for this information, it is updated
I don't know what to do, can anyone give me an idea?

REACT.JS how to detect only one of the cards is clicked from a component

I tried to add click handler on my code, the idea is when i click on my first card, the first card add new class "selected" nad when i click on my third card or else the third card or else will add new class "selected". There is a problem when i was clicking on any card it was always first card was selected. Please help me. Thank you.
Parent code
import React, { useState } from 'react';
import CardBus from '../CardBus/CardBus.component';
import './BusSelector.style.css'
function BusSelector() {
const [buses, setBuses] = useState([
{
busNumber: 1,
destination: 'Cibiru - Cicaheum',
stopTime: '09:20 - 09.45',
stopLocation: 'Jl.Jendral Sudirman',
isSelected: false
},
{
busNumber: 2,
destination: 'Cicaheum - Cibereum',
stopTime: '09:10 - 09.20',
stopLocation: 'Jl.Soekarno Hatta',
isSelected: false
},
]);
return (
<div className="bus-selector--container">
{buses.map((bus) => {
return <CardBus key={bus.busNumber} eachBus={bus} buses={buses} setBuses={setBuses} />
})}
</div>
);
}
export default BusSelector;
Child code:
import React from 'react';
import './CardBus.style.css';
import TimeProgressThin from '../../icon/Time_progress_thin.svg';
import PinLight from '../../icon/Pin_light_thin.svg';
function CardBus(props) {
const [isSelected, setIsSelected] = useState(false)
let { eachBus, buses, setBuses} = props;
const selectedHandler = () => {
if (isSelected) {
const card = document.querySelector('.card');
card.classList.add('selected');
return setIsSelected(!isSelected);
}
else {
const card = document.querySelector('.card');
card.classList.remove('selected');
return setIsSelected(!isSelected);
}
}
return (
<div key={eachBus.key} className="card" onClick={selectedHandler}>
<div className="bus--left">
<h1>{eachBus.busNumber}</h1>
</div>
<div className="bus--right">
<div className="title">
<h1>{`Armada ${eachBus.busNumber}`}</h1>
<h2>{eachBus.destination}</h2>
</div>
<div className="detail">
<div className="detail--item">
<div>
<img src={TimeProgressThin} alt="Time Progress Logo" />
</div>
<div className="detail_content">
<h3>Last stopped</h3>
<h3>{eachBus.stopTime}</h3>
</div>
</div>
<div className="detail--item">
<div>
<img src={PinLight} alt="Pin Light Logo" />
</div>
<div className="detail_content">
<h3>Location Stopped</h3>
<h3>{eachBus.stopLocation}</h3>
</div>
</div>
</div>
</div>
</div>
);
}
export default CardBus;
Allow multiple selections
function CardBus(props) {
const [isSelected, setIsSelected] = useState(false);
let { eachBus, buses, setBuses } = props;
return (
<div key={eachBus.key} className={`card ${isSelected ? 'selected' : ''}`} onClick={() => setIsSelected(!isSelected)}>
...
</div>
);
}
export default CardBus;
Allow single select
You can simplify the code a lot if you move the selected child logic to the parent.
Parent code:
function BusSelector() {
const [buses, setBuses] = useState([
{
busNumber: 1,
destination: 'Cibiru - Cicaheum',
stopTime: '09:20 - 09.45',
stopLocation: 'Jl.Jendral Sudirman',
isSelected: false
},
{
busNumber: 2,
destination: 'Cicaheum - Cibereum',
stopTime: '09:10 - 09.20',
stopLocation: 'Jl.Soekarno Hatta',
isSelected: false
},
]);
const [selectedBus, setSelectedBus] = useState(-1);
return (
<div className="bus-selector--container">
{buses.map((bus) => {
return <CardBus
key={bus.busNumber}
eachBus={bus}
buses={buses}
setBuses={setBuses}
onClick={() => setSelectedBus(bus.busNumber)}
isSelected={bus.busNumber === selectedBus} />;
})}
</div>
);
}
export default BusSelector;
Child code:
function CardBus(props) {
let { eachBus, isSelected, buses, setBuses, onClick } = props;
return (
<div key={eachBus.key} className={`card ${isSelected ? 'selected' : ''}`} onClick={onClick}>
...
</div>
);
}
export default CardBus;

Keydown is being pushed or outputted multiple times

I've been trying to learn React and I know my code structure is definitely not great but for some reason this code keeps outputting my letter I touch multiple times, it's as if its multiplying every tap I do, How can I fix this? I've been stuck on it for a couple hours now atleast and I just cant seem to figure it out even when I try to google it
Main content
import {useState} from 'react'
import './app.css'
import Guess from './Guess'
const guesses = [
[],
[],
[],
[],
[],
[]
]
const alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function App(props) {
const count = 1
const [keyPressed, setKeyPressed] = useState("");
const keydownHandler = (event) => {
const letter = String.fromCharCode(event.keyCode)
if (alphabet.includes(letter)) {
guesses[0].push(letter)
setKeyPressed(letter)
}
}
document.addEventListener("keydown", keydownHandler)
return (
<>
<div className='title'>
<h1>Wordle Clone</h1>
<p>By: Brady Smith</p>
</div>
<div className="container">
{guesses.map((items, index) => {
return (
<ol>
{items.map((subItems, sIndex) => {
return <li> {subItems} </li>;
})}
</ol>
);
})}
<Guess letter={keyPressed}/>
<Guess />
<Guess />
<Guess />
<Guess />
<Guess />
</div>
</>
);
}
export default App;
Guess.js
import React, { useState } from 'react'
const Guess = ({letter}) => {
return (
<>
<div className="guess">
<div className="letter1">
<h1>{letter}</h1>
</div>
<div className="letter2">
<h1></h1>
</div>
<div className="letter3">
<h1></h1>
</div>
<div className="letter4">
<h1></h1>
</div>
<div className="letter5">
<h1></h1>
</div>
</div>
</>
)
}
export default Guess
You have to subscribe to keyPress function in every lifecycle.
useEffect(() => {
document.addEventListener("keydown", keydownHandler);
return () => document.removeEventListener("keydown", keydownHandler);
});

Use same usestate hook for multiple icons

I have a two buttons in my react project (material ui icons) which are lowerarrow(both) and i made a use state and function to change upper arrow to lower arrow when it is clicked but i dont know how to use the same state for my another icon too, maybe using some id or something i dont know , right now i put {iconstate} in both the icons so both the icons are changing together i am trying to figure out how to change them individually without making new state and function here is my code :-
JSX:-
import React , {useState} from 'react';
import Weather_leftpanecss from './Weather_leftpane.module.css'
import KeyboardArrowDownIcon from '#mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '#mui/icons-material/KeyboardArrowUp';
export default function Weather_leftpane() {
const [iconstate, seticonstate] = useState(<KeyboardArrowDownIcon/>)
const [valuestate, setvaluestate] = useState(true)
const togglearrow = ()=>{
if(valuestate==true){
seticonstate(<KeyboardArrowUpIcon/>)
setvaluestate(false)
}
else{
seticonstate(<KeyboardArrowDownIcon/>)
setvaluestate(true)
}
}
return <div>
<div className={Weather_leftpanecss.main}>
<div id={Weather_leftpanecss.item_1}>Weather</div>
<div id={Weather_leftpanecss.item_2}>
<input type="text" placeholder='Search for city..' />
</div>
<div id={Weather_leftpanecss.item_3}>
<div className={Weather_leftpanecss.item_3_content} id="item_3_1">
Cities
</div>
<div className={Weather_leftpanecss.item_3_content} id="item_3_2" onClick={togglearrow} >
{iconstate}
</div>
</div>
<div id={Weather_leftpanecss.item_4}>
<div className={Weather_leftpanecss.item_4_content} id="item_4_1">
Settings
</div>
<div className={Weather_leftpanecss.item_4_content} id="item_4_2" onClick={togglearrow}>
{iconstate}
</div>
</div>
</div>
</div>;
}
css:-
.App {
font-family: sans-serif;
text-align: center;
}
(not the real css ,just added it because i have included it everywhere in my code with module)
Here you need to save the selected Id in the state.
import React , {useState} from 'react';
import Weather_leftpanecss from './Weather_leftpane.module.css'
import KeyboardArrowDownIcon from '#mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '#mui/icons-material/KeyboardArrowUp';
export default function Weather_leftpane() {
const [valuestate, setvaluestate] = useState(true)
const [id, setId] = useState(null);
const togglearrow = (val)=>{
if(valuestate==true){
setvaluestate(false)
}else{
setvaluestate(true)
}
setId(val);
}
return <div>
<div className={Weather_leftpanecss.main}>
<div id={Weather_leftpanecss.item_1}>Weather</div>
<div id={Weather_leftpanecss.item_2}>
<input type="text" placeholder='Search for city..' />
</div>
<div id={Weather_leftpanecss.item_3}>
<div className={Weather_leftpanecss.item_3_content} id="item_3_1">
Cities
</div>
<div className={Weather_leftpanecss.item_3_content} id="item_3_2" onClick={() => togglearrow('item_3_2')} >
{valuestate && id == 'item_3_2' ? KeyboardArrowUpIcon : KeyboardArrowDownIcon }
</div>
</div>
<div id={Weather_leftpanecss.item_4}>
<div className={Weather_leftpanecss.item_4_content} id="item_4_1">
Settings
</div>
<div className={Weather_leftpanecss.item_4_content} id="item_4_2" onClick={() => togglearrow('item_4_1')}>
{valuestate && id == 'item_4_1' ? KeyboardArrowUpIcon : KeyboardArrowDownIcon }
</div>
</div>
</div>
</div>;
}
Here you can use one state to achieve that, saving in one state the status of both buttons, which one is clicked or not and render the icon based on that status.
the toggleArrow function gets the itemId and uses it to set the updated value of the button. We use !prevState[itemId] since if it is false it will become true and vise versa.
I took the liberty of giving the state a more informative name than a generic name.
import React, { useState } from "react";
import Weather_leftpanecss from "./Weather_leftpane.module.css";
import KeyboardArrowDownIcon from "#mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "#mui/icons-material/KeyboardArrowUp";
export default function Weather_leftpane() {
const [clickedButtons, setClickedButtons] = useState({
item_3_2: false,
item_4_2: false
});
const toggleArrow = (itemId) => {
setClickedButtons((prevState) => ({
...prevState,
[itemId]: !prevState[itemId]
}));
};
return (
<div>
<div className={Weather_leftpanecss.main}>
<div id={Weather_leftpanecss.item_1}>Weather</div>
<div id={Weather_leftpanecss.item_2}>
<input type="text" placeholder="Search for city.." />
</div>
<div id={Weather_leftpanecss.item_3}>
<div className={Weather_leftpanecss.item_3_content} id="item_3_1">
Cities
</div>
<div
className={Weather_leftpanecss.item_3_content}
id="item_3_2"
onClick={() => toggleArrow("item_3_2")}
>
{clickedButtons["item_3_2"] ? (
<KeyboardArrowUpIcon />
) : (
<KeyboardArrowDownIcon />
)}
</div>
</div>
<div id={Weather_leftpanecss.item_4}>
<div className={Weather_leftpanecss.item_4_content} id="item_4_1">
Settings
</div>
<div
className={Weather_leftpanecss.item_4_content}
id="item_4_2"
onClick={() => toggleArrow("item_4_2")}
>
{clickedButtons["item_4_2"] ? (
<KeyboardArrowUpIcon />
) : (
<KeyboardArrowDownIcon />
)}
</div>
</div>
</div>
</div>
);
}

Resources