T
T
thistlemr112019-06-04 15:27:38
React
thistlemr11, 2019-06-04 15:27:38

How to change the state of one component in another?

5cf662efa3f8d131735377.png
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

, where WeatherPage is the element you want to show/hide, and ShowFlagList is the flag component.
This code does absolutely nothing. I'm new to React, so I have no idea other than changing the state to solve this problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-04
@thistlemr11

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} />
    </>
  );
};

I strongly recommend that you study the library documentation and go through the tutorial .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question