Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call methods on Reactjs components in the browser console or from an outside script?

Tags:

I am creating a leaflet map component, here is an example on plunker

http://plnkr.co/edit/LkghwOcby49XESdGb782?p=preview

here is the code

leaflet.jsx

/** @jsx React.DOM */
/*jshint indent: 2, node: true, nomen: true, browser: true*/
/*global React */

'use strict';
module.exports = React.createClass({
  getInitialState: function () {
    return {
      map: {}
    };
  },
  componentDidMount: function() {
    var map = L.map('map').setView([51.505, -0.09], 13);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    this.setState({map: map});
  },
  modifyMap: function (method, options) {
    this.setState({
      map : this.state.map[method](options.latLong, options.zoom, options.zoom_options)
    });
  },
  render: function () {
    return (
      /* jshint ignore:start */
      <div id="map"></div>
      /* jshint ignore:end */
    );
  }
});

map.html

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Leafy</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
    <!-- build:css(.tmp) styles/main.css -->
    <style>
      #map {
        height: 200px;
      }
    </style>
    <link rel="stylesheet" href="//cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">
    <!-- endbuild -->
  </head>
  <body>
    <!--[if lt IE 9]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <div class="container">
      <div id="leaflet"></div>
    </div>

    <!-- build:js scripts/vendor.js -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/react/0.11.0/react-with-addons.min.js"></script>
    <script src="//cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
    <!-- endbuild -->

    <!-- build:js scripts/main.js -->
    <script src="leaflet.jsx"></script>
    <!-- endbuild -->
  </body>
</html>

I would like to try and call the modifyMap method directly from the browser console or from any script on the page. I have tried to use statics but I am unable to find the Object which contains the modifyMap method. Is there an easy way to find this method or is there a better way of doing this with Reactjs? I also know that this is possible if the React class was created on this page instead of using module.exports in a separate file, I am hoping there is another way! Please help!

like image 976
earlonrails Avatar asked Aug 11 '14 18:08

earlonrails


People also ask

How do you call external js function in React?

First, create a React project by typing inside the terminal. To execute a external JavaScript function, we need to put the name of the function “alertHello” inside the square bracket. If you click on the alert button, it should popup the alert “Hello”. This imply we can call the external JavaScript function from React.

Can you use JSX outside of React?

Even though JSX had been around before React, it wouldn't have been nearly as popular without React picking it up. However, we can actually use JSX without React, and it's not that difficult either. The way React works is by configuring your bundler to convert JSX into calls to a createElement function.


2 Answers

If you want to call methods on the component instance, you need to make it available at some point during the component's lifecycle. For example, if you have only one such map on the page, you could do something like this:

componentDidMount: function() {
  // ...
  this.setState({map: map});
  window.map = this;
}

Now, you can access the component from the global map variable:

Screencast

Standard disclaimer: while this can be useful from time to time, especially when debugging, if you find yourself doing this very often, you should revisit your use of React—namely, you should generally pass properties into components, which the component would then use to update itself.

like image 162
Michelle Tilley Avatar answered Sep 17 '22 13:09

Michelle Tilley


call component methods externally:

var app= React.renderComponent( <app/>, document.getElementById('app') );
app.modifyMap(arg1, arg2) //or anything else

or from another component:

componentDidMount: function(){
    this.refs.myApp.modifyMap(arg1, arg2) // Etc.
},
render: function(){
    return <div>
        <App ref='myApp'/>
    </div>
}

but your 'modifyMap' method is anti thinking in react! use componentDidMount to affect map according to this.props only, and change them in Map parrent component. your Map instance should be something like

<Map center={[51.505, -0.09]} zoom={13} [...] /> 
like image 30
yarden Avatar answered Sep 18 '22 13:09

yarden