A
A
AlexFo902019-05-06 08:44:52
JavaScript
AlexFo90, 2019-05-06 08:44:52

How to initialize yandex map in react component along with page loading?

Good afternoon, please push the truth. there is a main component and there is a component with a map

class MainComponent extends React.Component {

}

class MapComponent extends React.Component {
handleScriptLoad = () => {
    const {ymaps} = window;
    ymaps.ready(this.init);
  }

  init = () => {
    const {ymaps} = window;
    const myMap = new ymaps.Map('map', {
      center: [55.76, 37.64],
      zoom: 5,
      controls: []
    });
    return myMap;
  }

render() {
    const instanceMap = this.init();
    return (
      <div>
        <Script
          url="https://api-maps.yandex.ru/2.1/?&lang=ru_RU"
          onLoad={this.handleScriptLoad}
        />
        <button onClick={() => какая-то функция(instanceMap)}>Add</button>
        <div id='map' className={styles.containerMap}></div>
      </div>
    )
  }

}

I need to initialize the map on page load right away. Since I need access to my map instance, I want to get it in the render method and then use it in the application. That is, add Placemark, etc. But at the time of rendering the render method, I still do not have access to ymaps, so it swears ... tell me how to fix it (put the loading into the MainComponent component or maybe use some kind of life cycle ??? )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Antonov, 2019-05-06
@AlexFo90

Use the componentDidMount() lifecycle and make a map call in it
https://metanit.com/web/react/2.6.php
ps: I'm not sure about the correct connection of the map in your code.
I suggest you check out a similar question. How to work with yandex map React?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question