Python plays with React JS

React.js, a JavaScript library for building user interfaces, and Python, a versatile programming language, can work together in various ways to create full-stack web applications. React JS is an open-source JavaScript library developed by Facebook. It is released under the MIT license, which means it is free for both personal and commercial use. You can freely use React JS in production applications without any licensing fees or restrictions.

The origins of React JS can be traced back to 2011 when Jordan Walke, a software engineer at Facebook, developed an early version of React called “FaxJS” for internal use. It was primarily created to solve the challenges of developing large-scale, complex user interfaces with high performance.

In 2013, React JS was open-sourced and made available to the public. Facebook wanted to share their solution to building efficient UI components with the wider development community. The open-source release of React JS gained significant popularity and attracted a large community of developers who contributed to its growth and evolution.

Since its initial release, React JS has undergone significant improvements and has become one of the most widely used JavaScript libraries for building user interfaces. It has been adopted by numerous organizations and is used in countless production applications across various industries. In addition to React JS, Facebook also developed React Native, a framework for building native mobile applications using React principles and codebase. React Native has its own ecosystem and community and has further expanded the reach and capabilities of React for mobile development.Here are a few approaches to integrating React.js and Python:

  1. RESTful API: You can build a backend API using Python, using frameworks like Flask or Django. The API can expose endpoints that handle data requests and interact with a database. React.js, on the frontend, can make HTTP requests to these API endpoints to fetch and manipulate data.
  • JSON-RPC or GraphQL: Instead of using RESTful APIs, you can use other protocols like JSON-RPC or GraphQL to communicate between React.js and Python. Libraries like `json-rpc` in Python or `Apollo` for GraphQL can be used to facilitate this communication.
  • Server-Side Rendering (SSR): React.js can be used for server-side rendering, where the initial rendering of the React components is done on the server using a library like Next.js or Gatsby. Python can handle the server-side rendering logic and provide data to the React components.
  • Microservices Architecture: In a microservices architecture, you can have separate services for frontend and backend. React.js can be used for the frontend, and Python services can be developed independently to handle specific functionalities. The services can communicate through APIs or message queues.
  • Websockets: If you require real-time communication between the frontend and backend, you can use websockets. Python libraries like `Flask-SocketIO` or `Django Channels` can be used on the backend, while React.js can utilize websocket libraries like `Socket.IO` or `WebSocket API` to establish a connection and exchange data in real-time.

If you have noticed you may find that these approaches are not mutually exclusive, and you can mix and match them based on your project requirements. Ultimately, the choice of how React.js and Python play together depends on the specific needs of your application and the expertise of your development team.

CONTENTS

React JS a chronology

War of generations React Vs Angular

Create a React JS application with Flask

Notes on deployment of this application

React JS example with web2py as the framework of your choice

Py4Web and React

Using React JS with Django an example

React JS a chronology

React.js, often referred to as React, is a popular JavaScript library for building user interfaces. It was developed by Facebook and was first deployed on Facebook’s newsfeed in 2011. Here’s a brief history of React.js:

2011: React’s development began when Jordan Walke, a software engineer at Facebook, created an internal prototype called “FaxJS” for Facebook’s newsfeed. This prototype aimed to improve the performance and user experience of Facebook’s web application.

2013: React was publicly released at the JSConf US conference in May 2013. It gained attention as an open-source project, and its philosophy of building reusable and composable UI components resonated with developers.

2015: React Native, a framework for building native mobile apps using React, was introduced. With React Native, developers could use React concepts to write mobile apps for iOS and Android platforms. It allowed code reuse between web and mobile applications.

2016: React Fiber, a complete rewrite of React’s core algorithm, was announced at the React.js Conf. React Fiber was designed to improve the performance, concurrency, and rendering capabilities of React, making it more efficient for complex and interactive UIs.

2018: React Hooks were introduced as a new feature in React version 16.8. Hooks allow developers to use state and other React features without writing class components, enabling a more concise and functional programming style.

2020: React 17 was released with no major changes to the API surface. It focused on providing a smooth upgrade path for existing React applications and improving compatibility across different versions of React.

2021: Concurrent Mode, a new set of features and APIs focused on improving performance and responsiveness, was introduced. Concurrent Mode allows React to work on large-scale applications by breaking up work into smaller, prioritizable units.

React.js has seen widespread adoption in the web development community due to its component-based architecture, virtual DOM, and efficient rendering capabilities. It has a thriving ecosystem with numerous libraries, tools, and frameworks built around it, making it a popular choice for building modern web applications.

War of generations React Vs Angular

React and Angular are both popular JavaScript frameworks for building web applications, and each has its own strengths and advantages. Here are some reasons why React is preferred by some developers over Angular:

  1. Flexibility and Simplicity: React is known for its simplicity and ease of use. It focuses on the view layer, providing a straightforward approach to building user interfaces. React allows developers to compose reusable UI components, making it highly flexible and enabling faster development.
  2. Virtual DOM: React utilizes a virtual DOM (Document Object Model), which is a lightweight copy of the actual DOM. By comparing the virtual DOM with the real DOM, React efficiently updates only the necessary parts of the UI, reducing the overall rendering time and improving performance.
  3. Community and Ecosystem: React has a large and vibrant community with extensive third-party libraries and components available. The React ecosystem offers a wide range of tools, such as state management libraries like Redux or MobX, routing libraries like React Router, and UI component libraries like Material-UI or Ant Design. This ecosystem provides developers with plenty of options and resources to enhance their React projects.
  4. Learning Curve: React has a relatively gentle learning curve, especially for developers familiar with JavaScript. It allows developers to leverage their existing JavaScript knowledge and doesn’t introduce many complex concepts or conventions. This simplicity and familiarity make it easier for new developers to start with React.
  5. React Native: React’s compatibility with React Native is a significant advantage. React Native allows developers to build native mobile apps for iOS and Android platforms using React principles and codebase. This means that developers can reuse a significant portion of their React code and skills to create mobile applications, providing a more efficient development process.
  6. Performance: React’s virtual DOM and efficient rendering mechanisms contribute to its performance advantages. The ability to selectively update only the necessary components in the UI results in faster rendering and a smoother user experience. React’s focus on performance has made it a preferred choice for building high-performance web applications.

Note that Angular also has its own advantages, such as a more opinionated and feature-rich framework, comprehensive documentation, and an integrated development environment (Angular CLI). The choice between React and Angular ultimately depends on the specific needs of the project, the preferences of the development team, and the ecosystem and tools that align best with the project requirements.

Create a React JS application with Flask

To implement React.js, you will need to write JavaScript code, as React.js is a JavaScript library. However, you can use Python as the backend language to handle data processing and serve the React.js frontend. Here’s an example of how you can set up a basic React.js application with a Python backend:

  1. Install Node.js: First, make sure you have Node.js installed on your system. You can download and install it from the official Node.js website (https://nodejs.org).
  2. Create a React.js Application: Open a terminal or command prompt and navigate to the directory where you want to create your React.js application. Then, run the following commands:
shell
npx create-react-app my-app
cd my-app

This will create a new React.js application using Create React App and navigate you into the project directory.

  1. Start the React Development Server: Once inside the project directory, start the React development server with the following command:
shell
npm start

This will launch the development server, and you should be able to see your React.js application running in your browser at http://localhost:3000.

  1. Set Up Python Backend: In a separate directory, create a Python backend for your React application. You can use frameworks like Flask or Django. Here’s an example using Flask:
  • Install Flask by running the following command:
shell
pip install flask
  • Create a file named app.py and add the following code:
python
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/data', methods=['GET'])
defget_data():
    data = {'message': 'Hello from the Python backend!'}
    return jsonify(data)
if __name__ == '__main__':
    app.run()

This simple Flask app defines a route /api/data that returns a JSON response.

  1. Connect React and Python: In your React.js application, you can make HTTP requests to the Python backend using the fetch API or libraries like Axios. Open the src/App.js file in your React.js project and modify it as follows:
javascript
importReact, { useEffect, useState } from'react';
functionApp() {
  const [data, setData] = useState('');
  useEffect(() => {
    fetch('/api/data') // Make a GET request to the Python backend
      .then((response) => response.json())
      .then((data) =>setData(data.message));
  }, []);
  return (   
      <h1>{data}</h1>
    </div>
  );
}
exportdefaultApp;

This code sets up a React component that fetches data from the /api/data endpoint of the Python backend and displays it on the page.

  1. Run the Python Backend: In a separate terminal or command prompt, navigate to the directory where you created the Python backend (app.py). Run the following command to start the Flask server:
shell
python app.py

The Python backend should now be running on http://localhost:5000.

With both the React development server and the Python backend running, you should be able to see the React.js application fetching data from the Python backend and displaying it on the page.

This example demonstrates a basic integration between React.js and Python, but there are various other techniques and patterns you can use depending on your project requirements.

Notes on deployment of this application

To deploy a React.js application with a Python backend, you’ll need to follow a few steps to ensure both the frontend and backend are properly deployed. Here’s a general guide to deploying this type of application:

  1. Build the React.js Application: Before deploying, you need to create a production-ready build of your React.js application. In your terminal, navigate to the root directory of your React project and run the following command:

shell

npm run build

This command generates an optimized and minified version of your React app in the build directory.

  1. Prepare the Python Backend: If you’re using a framework like Flask or Django, you need to ensure that your Python backend is configured for production deployment. This may involve setting environment variables, updating database settings, and configuring the server. Consult the documentation of your chosen framework for specific instructions.
  2. Choose a Hosting Provider: Select a hosting provider that supports both Python and Node.js applications. Some popular options include Heroku, AWS Elastic Beanstalk, DigitalOcean, or Vercel. Choose the one that best suits your needs in terms of pricing, ease of use, and scalability.
  3. Deploy the Python Backend: Follow the hosting provider’s documentation to deploy your Python backend. This typically involves creating a new application, setting up a server, configuring environment variables, and deploying your Python code. Make sure the backend is accessible and running correctly on the chosen hosting provider.
  4. Deploy the React.js Frontend: Depending on your hosting provider, you have different options for deploying the React.js frontend. Here are a couple of common approaches:
    • Deploying with the Backend: If your hosting provider supports serving static files and running backend services, you can deploy the React.js build as part of the Python backend deployment. Copy the contents of the build directory into a directory accessible by the backend server, such as a static directory. Ensure the backend is configured to serve these static files.
    • Separate Deployment: If you prefer to deploy the React.js frontend separately, you can use a static file hosting service like AWS S3, Netlify, or Vercel. Upload the contents of the build directory to the hosting service and configure it to serve the files as a static website.
  5. Connect the Frontend and Backend: If you deployed the React.js frontend separately from the backend, make sure to update any API URLs or endpoints in your React code to point to the correct backend server URL. This might involve modifying the URLs in the fetch or Axios requests within your React components.
  6. Test and Verify: Once both the frontend and backend are deployed, test your application thoroughly to ensure all functionality is working as expected. Verify that the React frontend can communicate with the Python backend and retrieve data correctly.

It is essential that you consider security practices such as enabling HTTPS, securing sensitive data, and implementing appropriate access controls depending on your deployment environment.

Each hosting provider has its own deployment process, so be sure to refer to their specific documentation for detailed instructions.

React JS example with web2py as the framework of your choice

Web2py is a Python web framework that follows the Model-View-Controller (MVC) architectural pattern. While React.js is primarily a frontend library, it can be integrated with Web2py to enhance the frontend capabilities of your application. Here’s a general approach to using React.js with Web2py:

1. Create a Web2py Application: Set up a Web2py application using the official documentation and make sure it’s running correctly. You can use the built-in development server or deploy it to a production server.

2. Add React.js to Web2py: In your Web2py project, create a folder (e.g., `static/react`) to store the React.js related files. You can either download React.js from a CDN or use a package manager like npm or yarn to install it locally and copy the necessary files to the `static/react` folder.

3. Build the React.js Application: Develop your React.js application separately in a dedicated directory (outside the Web2py project). Follow the React.js development practices to create components, handle state, and manage data.

4. Integrate React.js Components: Once you have the React.js application built, you need to integrate it into your Web2py views. Create a Web2py view file (e.g., `views/react.html`) and add the necessary HTML structure and placeholders for your React components.

5. Load React.js and Render Components: In the `views/react.html` file, include the necessary JavaScript files to load React.js and your built React application. Add a `<div>` element with an id to serve as the mounting point for your React components.

6. Configure Web2py Routes: Set up Web2py routes to map specific URLs to your React.js views. This allows Web2py to serve the React.js views and handle any backend API calls made by the React components. For example, you can configure a route in `routes.py` to point to the `react.html` view.

7. Create Backend APIs: If your React.js components need to communicate with the Web2py backend, you’ll need to create API endpoints in Web2py to handle these requests. This can be done by defining functions in the appropriate controllers and using the `@service.json` decorator to return JSON responses.

8. Fetch Data from Web2py Backend: Within your React.js components, use the `fetch` API or libraries like Axios to make HTTP requests to the Web2py backend API endpoints you created. Retrieve and handle the responses to update the React component state and display the data.

9. Test and Refine: Test the integration between Web2py and React.js, ensuring that data is correctly fetched and displayed in your React components. Debug and refine your code as needed.

This approach allows you to leverage the frontend capabilities of React.js while utilizing the backend functionality of Web2py. Remember to properly organize your code, separate concerns, and follow best practices for both React.js and Web2py development.

Let’s have a look at an example – Here’s a complete example of integrating React.js with Python 3.0 using the Web2py web framework:

  1. Set Up Web2py:
    • Download and install the latest version of Web2py from the official website.
    • Create a new Web2py application using the following command in your terminal:

shell

·  python web2py.py -a your_password -c your_app_name

·  Start the Web2py development server by running:

shell

  • python web2py.py -a your_password -c your_app_name -i 127.0.0.1 -p 8000
  • Open your web browser and go to http://127.0.0.1:8000/your_app_name to verify that the Web2py application is running correctly.

·  Set Up React.js Frontend:

  • Create a new directory for your React.js frontend inside the Web2py application’s static directory. For example, your_app_name/static/react.
  • Navigate to the static/react directory and initialize a new React app:

shell

npx create-react-app .

·  Update React.js Frontend:

  • Replace the contents of src/App.js in the React app with the following code:

javascript

import React, { useEffect, useState } from ‘react’;

function App() {

  const [data, setData] = useState(”);

  useEffect(() => {

    fetch(‘/your_app_name/default/api/data’) // Make a GET request to the Web2py backend API

      .then((response) => response.json())

      .then((data) => setData(data.message));

  }, []);

  return (

    <div>

      <h1>{data}</h1>

    </div>

  );

}

export default App;

·  Create Backend API in Web2py:

  • In your Web2py application, create a new file named default.py in the controllers directory.
  • Add the following code to the default.py controller:

python

import json

def api():

    data = {‘message’: ‘Hello from the Python backend!’}

    return json.dumps(data)

·  Create HTML Template:

  • Create a new file named react.html in the Web2py application’s views directory.
  • Add the following code to the react.html view:

html

<!DOCTYPE html>

<html lang=”en”>

  <head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>React Web2py Integration</title>

  </head>

  <body>

    <div id=”root”></div>

    <script src=”{{=URL(‘static’, ‘react/build/static/js/main.js’)}}”></script>

  </body>

</html>

·  Set Up Web2py Route:

  • Open the routes.py file in the Web2py application’s root directory.
  • Add the following route mapping to the routes.py file:

python

  •  

routes_in = (

    (‘/your_app_name/default/api/data’, ‘/your_app_name/default/api’),

)

  1. Run the Application:
    • Open your web browser and go to http://127.0.0.1:8000/your_app_name/default/react.
    • You should see the React.js application fetching data from the Web2py backend API and displaying it on the page.

That’s it! You now have a complete example of integrating React.js with Python 3.0 using the Web2py web framework. The React.js frontend communicates with the Web2py backend API to fetch data and display it on the webpage.

Now web2py guys would be familiar with py4web – Here we look at how to use this with py4web framework

Py4Web and React

Py4web is a Python web framework that follows the Model-View-Controller (MVC) architectural pattern. While React.js is primarily a frontend library, it can be integrated with Py4web to enhance the frontend capabilities of your application. Here’s a general approach to using React.js with Py4web:

  1. Create a Py4web Application: Set up a Py4web application using the official documentation and make sure it’s running correctly. You can use the built-in development server or deploy it to a production server.
  2. Add React.js to Py4web: In your Py4web project, create a folder (e.g., static/react) to store the React.js related files. You can either download React.js from a CDN or use a package manager like npm or yarn to install it locally and copy the necessary files to the static/react folder.
  3. Build the React.js Application: Develop your React.js application separately in a dedicated directory (outside the Py4web project). Follow the React.js development practices to create components, handle state, and manage data.
  4. Integrate React.js Components: Once you have the React.js application built, you need to integrate it into your Py4web views. Create a Py4web view file (e.g., views/react.html) and add the necessary HTML structure and placeholders for your React components.
  5. Load React.js and Render Components: In the views/react.html file, include the necessary JavaScript files to load React.js and your built React application. Add a <div> element with an id to serve as the mounting point for your React components.
  6. Configure Py4web Routes: Set up Py4web routes to map specific URLs to your React.js views. This allows Py4web to serve the React.js views and handle any backend API calls made by the React components. For example, you can configure a route in routes.py to point to the react.html view.
  7. Create Backend APIs: If your React.js components need to communicate with the Py4web backend, you’ll need to create API endpoints in Py4web to handle these requests. This can be done by defining functions in the appropriate controllers and using the @action decorator to return JSON responses.
  8. Fetch Data from Py4web Backend: Within your React.js components, use the fetch API or libraries like Axios to make HTTP requests to the Py4web backend API endpoints you created. Retrieve and handle the responses to update the React component state and display the data.
  9. Test and Refine: Test the integration between Py4web and React.js, ensuring that data is correctly fetched and displayed in your React components. Debug and refine your code as needed.

This approach allows you to leverage the frontend capabilities of React.js while utilizing the backend functionality of Py4web. Remember to properly organize your code, separate concerns, and follow best practices for both React.js and Py4web development.

I wouldn’t disappoint our Django guys so here’s a scaffolding for you

Using React JS with Django an example

Set Up Django:

  • Create a new Django project by running the following command in your terminal:

shell

django-admin startproject your_project_name

·  Navigate to the project directory:

shell

·  cd your_project_name

·  Start a new Django app within the project:

shell

python manage.py startapp your_app_name

·  Set Up React.js Frontend:

  • Install Node.js if you haven’t already. You can download it from the official website.
  • Create a new directory for your React.js frontend inside the Django app’s directory. For example, your_project_name/your_app_name/frontend.
  • Navigate to the frontend directory and initialize a new React app:

Shell

npx create-react-app .

·  Update React.js Frontend:

  • Replace the contents of src/App.js in the React app with the following code:

javascript

import React, { useEffect, useState } from ‘react’;

function App() {

  const [data, setData] = useState(”);

  useEffect(() => {

    fetch(‘/api/data’) // Make a GET request to the Django backend API

      .then((response) => response.json())

      .then((data) => setData(data.message));

  }, []);

  return (

    <div>

      <h1>{data}</h1>

    </div>

  );

}

export default App;

·  Create Backend API in Django:

  • Open the your_app_name/views.py file and add the following code:

python

from django.http import JsonResponse

def api(request):

    data = {‘message’: ‘Hello from the Python backend!’}

    return JsonResponse(data)

·  Configure URLs in Django:

  • Open the your_project_name/urls.py file and add the following code:

python

from django.urls import path

from your_app_name import views

urlpatterns = [

    path(‘api/data’, views.api, name=’api_data’),

]

·  Configure Django to Serve the React App:

  • Open the your_project_name/settings.py file and update the following settings:
    • Add ‘your_app_name’ to the INSTALLED_APPS list.
    • Set the STATICFILES_DIRS to include the React app’s build/static directory. For example:

python

·  STATICFILES_DIRS = [

    os.path.join(BASE_DIR, ‘your_app_name/frontend/build/static’),

]

·  Set the TEMPLATES setting to include the React app’s build/index.html file. For example:

python

TEMPLATES = [

    {

        …

        ‘DIRS’: [

            os.path.join(BASE_DIR, ‘your_app_name/frontend/build’),

        ],

        …

    },

]

·  Run the Application:

  • In your terminal, make sure you are in the project directory.
  • Start the Django development server:

Shell

python manage.py runserver

Open your web browser and go to http://localhost:8000.

You should see the React.js application fetching data from the Django backend API and displaying it on the page.

Well there you have it! You now have a complete example of integrating React.js with Python 3.0 using the Django web framework. The React.js frontend communicates with the Django backend API to fetch data and display it on the webpage.

Dhakate Rahul

Dhakate Rahul

23 thoughts on “Python plays with React JS

  1. Thanks for making me to acquire new tips about personal computers. I also have belief that one of the best ways to maintain your notebook computer in primary condition is a hard plastic-type case, or shell, that matches over the top of your computer. These kind of protective gear are generally model specific since they are made to fit perfectly in the natural outer shell. You can buy these directly from the seller, or through third party sources if they are readily available for your notebook computer, however don’t assume all laptop can have a covering on the market. Once again, thanks for your tips.

  2. Excellent blog here! Also your site loads up very fast!
    What web host are you using? Can I get your affiliate link to your host?
    I wish my site loaded up as quickly as yours lol

  3. I’m not that much of a online reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your website to come back in the future.
    Cheers

  4. Good way of describing, and fastidious paragraph to take data about my presentation subject, which i am going to
    convey in institution of higher education.

  5. Generally I don’t learn article on blogs,
    but I would like to say that this write-up very compelled me to take a look at and do so!
    Your writing style has been amazed me. Thank you, quite
    great post.

  6. When someone writes an piece of writing he/she maintains
    the idea of a user in his/her mind that how a user can understand it.
    Therefore that’s why this post is great. Thanks!

  7. Hello there! This post couldn’t be written any better!
    Reading this post reminds me of my good old room mate!
    He always kept chatting about this. I will forward this article to him.
    Pretty sure he will have a good read. Thanks for sharing!

  8. Howdy just wanted to give you a quick heads up.
    The words in your article seem to be running off the screen in Ie.
    I’m not sure if this is a format issue or something to do with internet
    browser compatibility but I figured I’d post to let you know.
    The style and design look great though! Hope you get the problem resolved soon. Many thanks

  9. I simply could not depart your web site before suggesting that I extremely enjoyed the usual information a person supply in your guests?
    Is gonna be back often in order to check up on new posts

  10. I for all time emailed this webpage post page to all my contacts,
    because if like to read it afterward my friends will
    too.

  11. Hi there! I know this is kind of off topic but I was wondering which blog platform are you using for this website?

    I’m getting fed up of WordPress because I’ve had issues with
    hackers and I’m looking at alternatives for another platform.

    I would be awesome if you could point me in the direction of a good platform.

  12. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish. nonetheless,
    you command get bought an nervousness over that
    you wish be delivering the following. unwell unquestionably come further
    formerly again as exactly the same nearly a lot often inside case you shield this hike.

  13. Nice post. I learn something totally new and challenging on blogs I stumbleupon on a
    daily basis. It will always be helpful to read through
    content from other authors and practice a little something from their sites.

  14. Greetings! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment
    form? I’m using the same blog platform as yours and I’m
    having problems finding one? Thanks a lot!

  15. Very nice post. I just stumbled upon your weblog and wished to mention that I have really enjoyed surfing around your weblog posts.
    In any case I will be subscribing in your rss feed and I’m hoping you write again soon!

  16. I do not even know how I ended up here, but I thought this post was great.
    I don’t know who you are but certainly you are going to a famous blogger
    if you aren’t already 😉 Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *