Tushant
Tushant

Reputation: 1584

Data passed as props is not shown in django and reactjs

I wanted to pass if username is authenticated or not from django template inside script tag which renders data for reactjs page so that i can use react router for routing user to login or logout. For this i did as below but no luck . I could not fetch value using this.props inside my react page.I get an error in console as "Uncaught TypeError: Cannot read property 'isUserAuthenticated' of undefined". What have i done wrong ? Sorry for my english if i could not explain clearly . I hope my code might enlighten you what I am trying to do.

index.html

{% load  staticfiles future i18n account rental_tags %}
    <div id="homepage">
    </div>
    <script type="text/javascript" src="{% static 'build/js/app.js'%}"></script>
    <script type="text/javascript">
      var data = {
            isUserAuthenticated:{% if request.user.is_authenticated %}true{% else %}false{% endif %}
        };

    $(function() {

      app.showHomePage("homepage",data);
    });

    </script>

index.js(entry point for webpack)

import React from 'react';
import ReactDOM from 'react-dom';
import Homepage from 'homepage/Homepage';

 window.app = {
        showHomePage: function(id,data){
        ReactDOM.render(
          <Homepage />, document.getElementById(id,data)
        );
}

Homepage.js

import React from 'react';
import Navbar from './components/Navbar';
import Body from './components/Body';
class Homepage extends React.Component {
  render() {
    console.log(this.props.data.isUserAuthenticated);
    return (
            <div className="layer">
              <Navbar />
              <Body />
            </div>
      );
  }
}

export default Homepage;
        }
    }

Upvotes: 2

Views: 1502

Answers (1)

Dan Prince
Dan Prince

Reputation: 30009

You're expecting the prop to show up on your Homepage component as this.props.data.isAuthenticated, but you're not passing any props to the component when you render it.

You need to pass the data parameter from the showHomepage method.

ReactDOM.render(
  <Homepage data={data}/>,
  document.getElementById(id)
);

You can also remove the second argument to document.getElementById (which only accepts one).

Upvotes: 2

Related Questions