Reputation: 1675
When I deploy my django project with
python manage.py runserver
, and my react app with npm start
,
I don't know which one is my "real project". I think the question boils down to client sided rendering vs server side rendering, and for now I want to go with server side rendering as I am more familiar with django than I am with react. That would mean I would have to set up urls and views with django/drf correct? If so, my questions are as follows...
How do I "invoke" react whenever I go to a url (for example, website.com/items). I want to return a list of all my items in a nicely formatted html file. I suspect this has to do with a template parameter in the path() function.
How do I prevent users from accessing api views (website.com/api/items), which is the url I use to handle api calls with django-rest-framework, but I don't want people to see this but also want react to "see" this.
Because I am doing server side rendering, is there anything else my react app needs to do other than do the correct http calls to my api urls and making my html template look pretty?
Project URLS:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('App.urls')),
path('api/',include('App.api.urls'))
]
App URLS:
urlpatterns = [
path('', views.index, name='index'), #nothing much here yet
]
Api URLS:
urlpatterns = [
path('item',views.ListItem.as_view())
]
My basic React App.js that just grabs all the items and displays them
class App extends Component {
state = {
items: []
};
async componentDidMount(){
try{
const res = await fetch('http://127.0.0.1:8000/api/item');
const items = await res.json();
this.setState({
items});
}
catch (e){
console.log(e);}
}
render(){
return(
<div>
{this.state.items.map(item =>(
<div key={item.id}>
<h1>{item.item}</h1>
<h1>{item.price}</h1>
<span>{item.description}</span>
</div>
))}
</div>
);
}
}
export default App;
Upvotes: 3
Views: 3054
Reputation: 557
If you would like to server side render your react app, you have to set up your javascript inside a template view in your django app. Right now you are running your react app and django app in different servers, so this is why you are not getting server side render for react app. this would involve creating react with webpack or pacel.
What I would do is bundle the react app inside a django view, that way is server side render.
I hope this makes sense.
Upvotes: 1