Answer the question
In order to leave comments, you need to log in
How to change the state of one component in another?
There is such a "project". So far, not stylized, nothing.
I'm trying to implement something like "by clicking on the flag, the top menu (where the button is) will be displayed, otherwise it is hidden." The code for this turned out to be something like this
import React,{Component} from 'react'
import ShowFlag from './ShowFlag'
import WeatherPage from "./WeatherPage";
class ShowFlagsList extends Component{
render(){
this.state={
openWeatherPage: <WeatherPage style={{display:'none'}}/>
};
//указываем начальное состояние нашего компонента
const {flags}=this.props
/*для всех элементов объекта (flags) применяем функцию мап,которая вернёт каждый элемент flag
с новой разметкой
*/
const flagList=flags.map (flag=>
<ShowFlag flag={flag} key={flag.id} className={ShowFlagsList} onClick={this.swapComponents} />
)
return(
<ul>
{flagList}
</ul>
)
}
swapComponents=()=>{
this.setState({
openWeatherPage: <WeatherPage style={{display:'block'}}/>
})
}
}
export default ShowFlagsList
Answer the question
In order to leave comments, you need to log in
import React, { useState, useCallback } from 'react';
import WeatherPage from './WeatherPage';
import Flag from './Flag';
const FlagsList = ({ onItemClick, flagsList }) => (
<ul>
{flagsList.map(flag => <Flag key={flag.id} flag={flag} onClick={onItemClick} />)}
</ul>
);
const Example = () => {
const [shouldShowWeather, setShouldShowWeather] = useState(false);
const toggleShowWeather = useCallback(() => {
setShouldShowWeather(state => !state);
}, []);
return (
<>
{shouldShowWeather && <WeatherPage />}
<FlagsList flagsList={flagsList} onItemClick={toggleShowWeather} />
</>
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question