Call React App from Outside Html


(Helium410) #1

Hi everybody :slight_smile: I’m glad to be part of this discussion forum.

By now I have some experience with react applications but I’ve been asked to do something I never did.
I have to build some react app which can be called from an outside html. For example, my react app would have some state (a list of articles) and the outside html should be able to have access to these data when the react app has done its work.

Do you think I can do this ?


(Mikayel) #2

You just need to pass your outside function via props, and call it from react

  function myFunction(data) {
    console.log(data)
  }

  ReactDOM.render(<MyApp myFunction={myFunction} />, mountNode);

(Theadd) #3

If you are the one who’s going to implement that “outside html” and responsible of keeping the state, just take a look at how example apps in react are implemented, as TODO list example, just look at it as it is a whole web page, not a single component from the page.

If your problem is somehow “tricky”, like you are trying to inject/integrate two different applications that you are not willing to partly rewrite in order to integregrate each other into one, you can just expose callbacks from react to the global context (window).

/* Inside a componentDidMount(){ } method of whatever has you need to change would be
   a "valid" place until you get deeper into react basic key concepts */
window.callMeBack = () => {
    // cheat codes goes here
}

(Helium410) #4

Thanks for your answer.
My react application is built like that :

I have the “root” in the public folder :

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>React Router App</title>

    <link rel="stylesheet" type="text/css" href="/index.css">
</head>

<body>
<div id="app-container"></div>
<script src="/bundle.js"></script>
</body>

</html>

And the index.tsx is :

render((
    <Provider store={store}>
        <Router history={history}>
            <Route path="/" component={App}>

                <IndexRoute component={PageHome}/>

                <Route path = "/test" component = {PageTest} />

                <Redirect from="*" to="/not_found"/>

            </Route>
        </Router>
    </Provider>
), document.getElementById('app-container'));

(Mikayel) #5

You can call the global function from your App, PageHome or PageTest.
Or move render to HTML and pass down the callback function via props.