How to use Flask to route with a React app? - javascript

I'm a React developer who's new to Flask. I'd like to route in backend with Flask and build frontend with React. My first scaffold looks like this:
Folder structure:
react-flask-app
-api
-app.py
-public
-index.html
-src
-pages
-Home.js
-Page1.js
-components
-Navbar.js
-App.js
App.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('../public/index.html')
Navbar.js:
const Navbar = () => {
return (
<>
<a href='/'>Home</a>
<a href='/page1'>Page 1</a>
</>
)
};
Home.js:
import Navbar from '../components/Navbar';
const Home = () => {
return (
<>
<Navbar />
<div>Homepage</div>
</>
)
}
Page1.js
import Navbar from '../components/Navbar';
const Page1 = () => {
return (
<>
<Navbar />
<div>Page 1</div>
</>
)
}
When I run the React app, I can switch between http://localhost:3000/ and http://localhost:3000/page1 by clicking the Navbar buttons, but it does not display Page1, since I've not set routing yet.
My question is, I know Flask can be used for routing, how can I use Flask to route and link to each page in this case?

To tell react to proxy any requests to Flask, add a proxy field to your package.json, e.g
"proxy": "http://localhost:5000",
Then use ajax, fetch from within your components to access your API.
More Information can be found in Proxying in development

Related

Router of React and Django could be co-existed?

I integrate React with Django.
So when accessing http://localhost:8000/
my django jump to
def index(request: HttpRequest) -> HttpResponse:
return render(request, 'index.html', context)
Rect top page
and index.js, create the element where id=app
import React from 'react'
import ReactDOM from 'react-dom';
import App from './components/App.js'
ReactDOM.render(
React.createElement(App),
document.getElementById('app')
);
Then I set the /top under react router.
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path={`/top`} element={<TopPage />} />
</Routes>
</BrowserRouter>
);
};
export default App;
However when using http://localhost:8000/top it goes to django url.
What I want to do is using /admin for django though, pass other urls except admin to React.
Is there any practice to do this??

How to retrieve some data from API and use it in all the pages of a NexJS application before rendering on client side?

I have a NextJS application where I have a home page (index.js) and two other pages About(about.js) & Contact Us(contact.js).
I have created a BaseLayour.js file with is wrapping NextJS's MyApp component in _app.js file.
import React from "react";
import BaseLayout from "../layouts/BaseLayout";
function MyApp(props) {
const { Component, pageProps } = props;
return (
<BaseLayout>
<Component {...pageProps} />
</BaseLayout>
);
}
export default MyApp;
This BaseLayout component looks like this -
import React from "react";
import SEO from "../components/SEO";
import Header from "../components/Header";
import Footer from "../components/Footer";
function BaseLayout(props) {
const { children } = props;
return (
<div>
<SEO />
<Header />
{children}
<Footer />
</div>
);
}
export default BaseLayout;
As you can see above in the BaseLayout file, there is an SEO component (React). It contains some common metadata for all the pages. I have an API(api/getmetadata/) that delivers all the metadata in JSON format.
This metadata is supposed to load on the server-side so that the page will be optimized for SEO.
How can we call the API in order to retrieve the data on each request but only on the server-side?
What I have tried till now -
Tried calling API in the SEO component itself, but it is not running on the server-side as it is just a React component.
Tried creating a React context, and called the API from SEO/BaseLayout components, the API call is still not being made from the server-side.
Tried using getServerSideProps in the index.js page to call the API and retrieve the data, which worked perfectly, but the problem is we need to share the data between all the pages, not just the index.js home page.
Any help will be appreciated, If we can somehow make the API call and retrieve the data in the SEO component, it will solve our problem.
Thank you in advance guys.

How to create website endpoints based on search results?

I'm building a ReactJS website as part of a web dev bootcamp project.
I made a search feature using flask routes between the reactjs endpoints (../Language.js) and my Sqlite3 database.
http://localhost:3000/kanjisearch
How do I make the result of a search into an endpoint itself though? For example if a user searches for "german verbs" the browser displays something along the lines of:
http://localhost:3000/kanjisearch?=german+verbs
I want this so that when users hit the forward or back arrows on the browser, it takes the user to the previous search, NOT the previous page they were on.
Can I do this is react/javascript? Something else?
Thank you.
yes you can, you can use react-router-dom library
just do yarn add react-router-dom and create a route.js file and do the following
import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import someScreen from "../somewhere" // this would be your Screen that you wanna show
const Routes = () => {
return (
<Router>
<Switch>
<Route path="/container/language/:language" component={someScreen} />
</Switch>
</Router>
);
};
export default Routes;
after that you have to fix your app.js file as the following
import React from 'react';
import './App.css';
import Routes from './router '; //the location of your router
function App() {
return (
<div className="App">
<header className="App-header">
<Routes/>
</header>
</div>
);
}
export default App;
go to your component and do export default withRouter(someScreen)
In your screen Since you have now a connected Class (to the routing) you can access match inside your props, this props is created by react-router and contains informations about what matched in this route : For exemple match.params.language would contains the :language from the route, meaning if u have /german+verbs
and now you can use the url like http://localhost:3000/container/language/german+verbs and then german+verbs
your parameters would be passed to your component as as
match.params = {
language: 'language+verbs'
}
use this is in your compDidMount method
Well... what language do you want to use? :-) . You can do it in any of those you mentioned.
Since you mentioned ReactJS first, you can do it in javascript by using the window.location object. Just set and read the hash. BTW the hash can be anything and is ignored by the browser, but your JS can look at it. Your url would look something like this:
http://localhost:3000/container/language/Language#search=german+verbs.

Next.js hangs while setting initial props on server-side

I am trying to set up SSR with Nextjs.
I have following code, where I am fetching json data and binding them as initial props.
When I am in development mode all works correctly, when I deploy to the server fetching works only on client-side (when I navigate from other view).
If I try to load directly the page with fetching, server hangs, no error.
I should add that all is running inside Docker container, but I guess it should not matter at this case.
Here is code
import React from 'react'
import { get } from 'axios'
import Layout from '../components/Layout/Layout'
import WorkSingle from '../components/Work/WorkSingle/WorkSingle'
import DocumentTitle from '../hoc/DocumentTitle/DocumentTitle'
const Work = (props) => {
let works = 'Loading...'
if (props.workData.length > 0)
works = props.workData.map(work => (
<WorkSingle
img={work.image}
url={work.url}
title={work.title}
key={work.title}
/>
))
return (
<Layout>
<DocumentTitle title='Some page title' />
<section id="work">
<h1 className="font_title">WORK</h1>
<div className="row">
{works}
</div>
</section>
</Layout>
)
}
Work.getInitialProps = async () => {
const response = await get('VALID_URL')
if (response && response.data)
return { workData: response.data.work }
return {}
}
export default Work
I have solved it, problem was that i wanted to fetch static data from the same server which is serving app, for some reason when server tried to fetch from itself it stuck, I put the resource I am fetching to another server for now and it solved problem.
I was mocking the data via static .json file, I guess when I create actual API endpoint it will work from the same server too.

React SSR dynamically import components according to API response

I am building SSR React app with razzle tool. Server is using express framework. I would like to load React components dynamically according to value included in API response.
I have folder structure like:
views
- default
-- Home.js
- theme1
-- Home.js
I am using SSR. On the server I have
const markup = renderToString(
<Provider store={store}>
<StaticRouter context={context} location={req.url}>
<App theme={theme} />
</StaticRouter>
</Provider>
);
Inside App component, I need to import component from corresponding subfolder or if its absent than import default component from the default subfolder. There can be many theme subfolders so I can't import all the components manually.
Should this by done on server by express or is there another way?
Thanks
Are you looking for something like this? I'm not quite sure if you are using server side rendering.
import DefaultComponent from './views/default.js';
import Theme1Component from './views/theme1.js';
this.state = {
visibleDefault: true
}
You can then simply update the state base on the response.
Then in your render you can have this
render(){
return(
{ visibleDefault ? <DefaultComponent/> : <Theme1Component/> }
)
}

Categories