new
new

Reputation: 377

How do I write script in React index.js?

I've been using basic HTML/CSS/JS so far, and now I tried using React/Gatsby. I got API code from Kakao and confirmed the following code is working in index.html:

<body>
    <div id="map" style="width:1000px;height:500px;"></div>

    <script src="https://dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608"></script>
    <script>{
      var mapContainer = document.getElementById('map'),
        mapOption = {
          center: new kakao.maps.LatLng(37.56591, 126.97894),
          level: 4,
          mapTypeId : kakao.maps.MapTypeId.ROADMAP
        };

      var map = new kakao.maps.Map(mapContainer, mapOption);

    }</script>
</body>

Since I'm trying React/Gatsby framework, I have to somehow reformat that script to index.js. HTML can be easily copy/pasted to return function, but I don't know how to write the above script in React index.js.

import React from "react"

export default class Home extends React.Component {
  render() {
  return (
    <div style={{ color: `purple` }}>
      <p>Welcome to donghwankim.com!</p>
      <p>Powered by Gatsby</p>
      <div id="map" style={{"height" : "1000px", "width" : "500px"}}></div>

      <script src="https://dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608"></script>
      <script>{
        var mapContainer = document.getElementById('map'), 
          mapOption = {
            center: new kakao.maps.LatLng(37.56591, 126.97894), 
            level: 4, 
            mapTypeId : kakao.maps.MapTypeId.ROADMAP 
          };

        var map = new kakao.maps.Map(mapContainer, mapOption);

      }</script>
    </div>
  )}
}

Few things I tried:

  1. Just copy paste script like above. In this case, I get syntax error from the copied script:

Unexpected token. Did you mean {'}'} or &rbrace;?

  1. Use dangerouslySetInnerHTML. There is no syntax error, but the map API is not working properly.

Thank you.

Upvotes: 0

Views: 1138

Answers (2)

Ferran Buireu
Ferran Buireu

Reputation: 29320

2022 update

Since the release of the Script Gatsby component (powered by Partytown) it's much easier adding third-party scripts. Just:

import React from "react"
import { Script } from "gatsby"

function YourPage() {
  return <Script src="https://my-example-script" />
}

export default YourPage

There's a lot of implementation there.

First of all, you need to load your script asynchronously using <Helmet> tag by using:

import React from "react"
import Helmet from "react-helmet"

export default class Home extends React.Component {
  render() {

  return (
    <div style={{ color: `purple` }}>
      <Helmet>
        <script src="https://dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608" type="text/javascript"/>
      </Helmet> 
      <p>Welcome to donghwankim.com!</p>
      <p>Powered by Gatsby</p>
      <div id="map" style={{"height" : "1000px", "width" : "500px"}}></div>
    </div>
  )}
}

Because of the asynchronous of your issue, you need to load a <div> container for your map and wait for its load, then you need to pass your map options. The preferred method in React, rather than document.getElementById (or similar), what retrieve directly values from the DOM, is using references. You'll need to use a componentDidMount() lifecycle to achieve it, since it's a method invoked that triggers immediately after a component is mounted (inserted into the tree):

import React from "react"
import Helmet from "react-helmet"

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
 
  componentDidMount(){
  const map= this.myRef.current;
  const mapOption = {
    center: new kakao.maps.LatLng(37.56591, 126.97894), 
    level: 4, 
    mapTypeId : kakao.maps.MapTypeId.ROADMAP 
  };

  const yourMap = new kakao.maps.Map(map, mapOption);
 }

  render() {

  return (
    <div style={{ color: `purple` }}>
      <Helmet>
        <script src="https://dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608" type="text/javascript"/>
      </Helmet> 
      <p>Welcome to donghwankim.com!</p>
      <p>Powered by Gatsby</p>
      <div id="map" ref={this.myRef}  style={{"height" : "1000px", "width" : "500px"}}></div>
    </div>
  )}
}

Note: you may need to unmount the map to avoid excessive resource consumption. It depends on how the library is implemented and its documentation.

Recommended readings/references:

Upvotes: 2

Nicky McCurdy
Nicky McCurdy

Reputation: 19524

It seems like part of this script will need to be rewritten for React. You should look for a library for this that supports React. If there isn't one, you can use DOM refs to access the mapContainer without document.getElementById. Alternatively if you just want to use this script as-is, you can use a simpler static site generator like Jekyll that doesn't require you to use React.

Upvotes: 2

Related Questions