Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable in index.html to react components

I am making a project using Django and React. I fetch the data from Twitter API from Django and I want to show the data in frontend. I pass the data from django views.py to index.html as a javascript variable. Then I want to present it in the Landing.js in Components folder. I used React router and I Landing and Main page are pages that I am routing to so far. I have not figured out how to pass the data from a single html file to Javascript components in React

Thanks in advance

<!-- index.html -->
<section class="section">
    <div class="container">
          <div id="app" class="columns"><!-- React --></div>
    </div>
  </section>
  <script type="text/javascript">
    window.myVar = "{{context.near.text}}";
    //data can be passed from the Django.views.py
    
  </script>

  {% load static %}
  <script src="{% static 'frontend/main.js' %}"></script>

//Landing.js js components
import React, { Component } from 'react';

class Landing extends Component {
    componentDidMount() {
        console.log(window.myVar); //undefined
        console.log(this.myVVar); //undefined
        
        
    }
    
    render(){
        return (
            <div>

                
                
            </div>
        )
    }
}

export default Landing;

This is my tree structure

this is context I pass from Django views.py

this is a variable I want to pass to "LANDING" componentsThis is "Landing.js" components I want to show the variables

like image 774
user9626571 Avatar asked Oct 21 '25 05:10

user9626571


1 Answers

Create a new property in the window object maybe window._DEFAULT_DATA and pass it the serialized data from Django in your view.

In the head tag in HTML

<script>
    window._DEFAULT_DATA = 'Data parsed in string'
 </script>

Then when you want to use it, just use JSON.parse to have a new JSON.

like image 199
mcssym Avatar answered Oct 23 '25 17:10

mcssym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!