4

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

2
  • it's possible but don't do this - react is not another template engine - let your app fetch data from your api Commented Sep 23, 2018 at 8:39
  • I have the same problem. Have you figured out how to do that? Commented Apr 2, 2020 at 9:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Suppose you want to access 'tweets' field in the data, you have to parse like const data = JSON.parse(window._DEFAULT_DATA); and access just with data.tweets
Try to make console.log(window._DEFAULT_DATA) just after you set it to be sure all is normal!!!
2

index.html:

<script>
localStorage.setItem('data', data)
</script>

React component:

let data = localStorage.getItem('data')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.