Search code examples
javascripthtmlreactjsastronomy

Using Aladin Lite app (not built for React) in React app


I would like to use the Aladin Lite app on my React app.

When building a site without React, it is very simple to embed the app in a div by doing:

<!-- include Aladin Lite CSS file in the head section of your page -->
<link rel="stylesheet" href="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css" />

<!-- you can skip the following line if your page already integrates the jQuery library -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js" charset="utf-8"></script>

<!-- insert this snippet where you want Aladin Lite viewer to appear and after the loading of jQuery -->
<div id="aladin-lite-div" style="width:400px;height:400px;"></div>
<script type="text/javascript" src="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.js" charset="utf-8"></script>
<script type="text/javascript">
    var aladin = A.aladin('#aladin-lite-div', {survey: "P/DSS2/color", fov:60});
</script>

Where you then have an object aladin to use in Javascript.

How would I go about using this app on my React page? It was not built for React and uses jquery.

I need to be able to access its props to change the field of view of the sky which in Javascript is done by:

aladin.setFov(1)

Would this be a good time for React portals?

Thank you.


Solution

  • Create a React component that will render Aladin sky map (so there will be no Aladin anywhere else). Then, you can define and configure aladin inside componentDidMount (if you are using class components) or React.useEffect (if you are using hooks).

    Index.html:

    ...
    <head>
       <link rel="stylesheet" href="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css" />
    
       <!-- you can skip the following line if your page already integrates the jQuery library -->
       <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js" charset="utf-8"></script>
    
       <!-- insert this snippet where you want Aladin Lite viewer to appear and after the loading of jQuery -->
       <script type="text/javascript" src="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.js" charset="utf-8"></script>
    </head>
    ...
    

    Aladin.jsx:

    const Aladin = () => {
    
        React.useEffect(() => {
            let aladin = A.aladin('#aladin-lite-div', { survey: 'P/DSS2/color', fov:60 })
            aladin.setFov(1)
        }, [])
    
        return (
            <div id='aladin-lite-div' style={{ width: '400px', height: '400px' }} />
        )
    }
    
    export default Aladin
    

    Then, everywhere you want to render Aladin sky map:

    import Aladin from './Aladin'
    ...
    <Aladin />