{"id":2210,"date":"2022-01-25T17:21:22","date_gmt":"2022-01-25T17:21:22","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2210"},"modified":"2022-01-25T17:21:22","modified_gmt":"2022-01-25T17:21:22","slug":"a-python-developers-guide-to-react","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2210","title":{"rendered":"A Python developer\u2019s guide to React"},"content":{"rendered":"\n<p>Although the most popular JavaScript library for creating user interfaces is React, learning how to use this library as a Python developer can be a long and tough process.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>While you can watch and read all the React tutorials possible to understand this library, it can be daunting if you don\u2019t know the appropriate path or step-by-step approach.<\/p>\n\n\n\n<p>This is because React uses a very different syntax and data structures than Python, which makes it difficult for Python developers to adapt to.<\/p>\n\n\n\n<p>In this article, we\u2019ll map out a road plan for getting started with React, as well as the core prerequisites for diving into React as a Python developer. We will also create a contact manager application with Flask (a Python web framework) and React as an example.<\/p>\n\n\n\n<p>Before starting, you should have knowledge of HTML, CSS, JavaScript, and Python.<\/p>\n\n\n\n<h2>Intro to React<\/h2>\n\n\n\n<p>Facebook created and maintains the React JavaScript library for designing user interfaces. It has grown in popularity in recent years due to its ability to bring the power of reactive and declarative programming to the realm of frontend development.<\/p>\n\n\n\n<p>React has also made it easier to consider user interface code and its programming paradigm encourages modular and reusable code.<\/p>\n\n\n\n<p>It\u2019s crucial to understand that React is nothing more than JavaScript.<\/p>\n\n\n\n<p>React isn\u2019t a standalone programming language or a domain-specific framework that takes years to understand. It has a simple API with just a few functions and concepts to master before you can use it to create web apps.<\/p>\n\n\n\n<p>Let\u2019s learn about some React concepts that will be important to understand in your journey of building web applications with React.<a href=\"https:\/\/blog.logrocket.com\/python-developers-guide-react\/\"><\/a><\/p>\n\n\n\n<h3>React components<\/h3>\n\n\n\n<p>Components are reusable chunks of code that are self-contained. They accomplish the same thing as JavaScript functions, except they act independently and return HTML.<\/p>\n\n\n\n<p>They can be related to Python\u2019s object-oriented programming (OOP) because both Python and JavaScript showcase the inheritance of data models.<\/p>\n\n\n\n<p>However, in OOP, the data isn\u2019t limited because any object can be created out of a Python class, unlike React components where data is limited to a set of other components. Also, React components can hold data for their own state, which is not the same for Python classes.<\/p>\n\n\n\n<p>In React, components can break a web application into separate parts with distinct functions. For example, you can create a component for the header of the web application and another for the navigation menu, reusing it on other pages of your application.<\/p>\n\n\n\n<h4>Component architecture<\/h4>\n\n\n\n<p>In Python, there is no special hierarchy for how classes are used. However, React components work in a particular hierarchy.<\/p>\n\n\n\n<p>We know that we can call and render components in other components. The component is called the child component, while the one that calls the child component is called the parent component. This is called a parent-child relationship.<\/p>\n\n\n\n<p>You will learn later in this article how important knowing this architecture is to data transfer between components.<\/p>\n\n\n\n<h4>Class components<\/h4>\n\n\n\n<p>A class component is a component that inherits the features from&nbsp;<code>React.Component&nbsp;class<\/code>.<\/p>\n\n\n\n<p>Below is an example of a class component:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class Header extends React.Component {\n  render() {\n    return &lt;h2&gt;Hello, I am a header!&lt;\/h2&gt;;\n  }\n}<\/pre>\n\n\n\n<p>In the class component above, we included the&nbsp;<code>extends&nbsp;React.Component<\/code>. This statement adds a&nbsp;<code>React.Component<\/code>&nbsp;inheritance to the component, giving it access to&nbsp;<code>React.Component<\/code>&nbsp;functionalities.<\/p>\n\n\n\n<p>The component also requires the&nbsp;<code>render()<\/code>&nbsp;function, which returns HTML, to render the data in it.<\/p>\n\n\n\n<p>The equivalent of the class component in Python is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class MyComponent(Component):\n    def __init__(self):\n        super().__init__()\n\n    def render(self):\n        return \"Hello, I am a heder\" ;<\/pre>\n\n\n\n<h4>Functional components<\/h4>\n\n\n\n<p><a href=\"https:\/\/blog.logrocket.com\/react-pure-components-functional\/\">A functional component, like a class component, returns HTML<\/a>&nbsp;and operates similarly, but functional components can be constructed with significantly less code, are easier to grasp due to their simple syntax, and are favored in this tutorial:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function Header() {\n  return &lt;h2&gt;Hello, I am a header!&lt;\/h2&gt;;\n}<\/pre>\n\n\n\n<p>Below is the Python equivalent:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def Header() {\n  return \"Hello, I am a header!\";\n}<\/pre>\n\n\n\n<h4>JSX<\/h4>\n\n\n\n<p>Although the&nbsp;<code>&lt;h1&gt;<\/code>&nbsp;and&nbsp;<code>&lt;div&gt;<\/code>&nbsp;tags look the same as HTML tags, they are not.&nbsp;<a href=\"https:\/\/blog.logrocket.com\/diving-into-the-new-jsx-transform\/\">JSX is a syntactic extension to JavaScript<\/a>&nbsp;that contains these tags and was designed by the React team to enable inline HTML-like markup in JavaScript components.<\/p>\n\n\n\n<p>These are similar to the Python&nbsp;<a href=\"https:\/\/pypi.org\/project\/Jinja2\/\">Jinja<\/a>&nbsp;templating engine.<\/p>\n\n\n\n<p>There are a couple of key differences between JSX and HTML tags. The first is simply that the&nbsp;<strong><code>class<\/code><\/strong>&nbsp;keyword is now&nbsp;<code>className<\/code>.<\/p>\n\n\n\n<p>Secondly, in HTML, we use strings like the following to define inline styles:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;h1 style=\"color: hotpink; font-size: 12px\"&gt;Hello&lt;h1&gt;<\/pre>\n\n\n\n<p>However, in JSX, we utilize camel-cased objects:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;h1 style=\"color\": \"hotpink\", \"fontSize\": \"12px\"&gt; Hello &lt;\/h1&gt;<\/pre>\n\n\n\n<p>And finally, variables can be added in our JSX markup to be rendered by wrapping a variable in:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">render() {\n    var myText = 'Hello!';\n    return (\n          &lt;h1&gt;{myText}&lt;\/h1&gt;\n    );\n}<\/pre>\n\n\n\n<p>Other React classes can be referenced in addition to HTML elements like&nbsp;<code>&lt;h1&gt;<\/code>&nbsp;and&nbsp;<code>&lt;div&gt;<\/code>. In our&nbsp;<code>src\/demo\/App.js<\/code>, for example, we render the&nbsp;<code>ExampleComponent<\/code>&nbsp;component by accessing it as&nbsp;<code>&lt;ExampleComponent&gt;<\/code>.<\/p>\n\n\n\n<h4>Styling components<\/h4>\n\n\n\n<p>There are three ways to&nbsp;<a href=\"https:\/\/blog.logrocket.com\/styling-in-react-4-ways-style-react-app\/\">style your React components<\/a>: using plain CSS, inline styles with JavaScript-style objects, or creating styled-components.<\/p>\n\n\n\n<h5>Using plain CSS to style<\/h5>\n\n\n\n<p>In the first way to style React components, which is using plain CSS, you must create a regular CSS file and import it into your React component. After importing it, you must add the class names for their corresponding HTML or JSX elements for the styles.<\/p>\n\n\n\n<p>Below is an example for the CSS header style:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">.header {\n  padding: 60px;\n  text-align: center;\n  background: #1abc9c;\n  color: white;\n  font-size: 30px;\n}<\/pre>\n\n\n\n<p>Then we have the header component:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react';\nimport PropTypes from 'prop-types';\nimport '.\/Header.css';\n...\nexport default function Alert() {\n  return(\n    &lt;div className=\"header\"&gt;\n      &lt;h2&gt;React Header&lt;\/h2&gt;\n    &lt;\/div&gt;\n  )\n}<\/pre>\n\n\n\n<h5>Using JavaScript-style objects<\/h5>\n\n\n\n<p>In the second method, you must remove the imported CSS file and create an object that has a padding of&nbsp;<code>20<\/code>&nbsp;and pass the object to the div using the style attribute:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react';\n\nfunction Header() {\n  const wrapper = {\n    padding: 20\n  };\n\n  return(\n    &lt;div style={wrapper}&gt;\n      &lt;h1\n    Header.\n      &lt;\/h1&gt;\n    &lt;\/div&gt;\n  )\n}\n\nexport default Header;<\/pre>\n\n\n\n<p>It\u2019s worth noting that you don\u2019t need to provide pixels as the padding unit. By default, React transforms this into a string of pixels. If you want a certain unit, write it as a string. So, for example, if you wanted the padding to be a percentage, it would be&nbsp;<code>padding:&nbsp;`20%`<\/code>.<\/p>\n\n\n\n<h4>Using styled-components<\/h4>\n\n\n\n<p>The third way to style your components is&nbsp;<a href=\"https:\/\/blog.logrocket.com\/benefits-using-styled-components-react\/\">by creating styled-components<\/a>. In this method, you must create styled objects, attach them, and wrap your JSX elements.<\/p>\n\n\n\n<p>Styled-components is a development package for React and React Native. It allows you to use component-level styles in your apps and they integrate JavaScript with CSS using a technique known as CSS-in-JS.<\/p>\n\n\n\n<p>Styled-components are built on tagged template literals, which implies that actual CSS code is written between backticks when styling components. Developers can reuse their CSS code from one project to the next as a result of this.<\/p>\n\n\n\n<p>When utilizing styled-components, there is no need to map your built components to external CSS styles.<\/p>\n\n\n\n<p>You can install styled-components using the npm command below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">npm i styled-components@4.1.3<\/pre>\n\n\n\n<p>Below is an example of how to use them in our React code:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react';\nimport styled from 'styled-components';\n\n\/\/ Button component that'll render an &lt;a&gt; tag with some styles\nconst Button = styled.a`\n  background-colour: teal;\n  color: white;\n  padding: 1rem 2rem;\n`\nconst App = () =&gt; {\n  return (\n    &lt;Button&gt;I am a button&lt;\/Button&gt;\n  )\n}\nexport default App;<\/pre>\n\n\n\n<p>You\u2019ll see that when constructing a React functional component, you can specify the name of the component with the variable type and its name, as in&nbsp;<strong><code>const&nbsp;Button<\/code><\/strong>.<\/p>\n\n\n\n<p>We imported&nbsp;<code>styled<\/code>&nbsp;above, which offers us the styled-components capabilities. Also, the&nbsp;<code>a<\/code>&nbsp;after&nbsp;<code>styled<\/code>&nbsp;signifies the anchor HTML element,&nbsp;<code>&lt;a&gt;<\/code>. When declaring a styled-component, you can use any HTML element like&nbsp;<code>&lt;div&gt;<\/code>,&nbsp;<code>&lt;h1&gt;<\/code>, or&nbsp;<code>&lt;p&gt;<\/code>.<\/p>\n\n\n\n<h3>States<\/h3>\n\n\n\n<p>A state object is integrated into React components.&nbsp;<a href=\"https:\/\/blog.logrocket.com\/modern-guide-react-state-patterns\/\">The state object<\/a>&nbsp;is where you keep the component\u2019s property values and the component rerenders when the state object changes:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React, {useState} from \"react\";\n \nconst MyComponent = () =&gt; {\n    const [value, setValue] = useState(1);\n    return (\n        &lt;div&gt;\n            &lt;p&gt;{value}&lt;\/p&gt;\n            &lt;button onClick={() =&gt; setValue((value + 1))}&gt;Increment Value&lt;\/button&gt;\n        &lt;\/div&gt;\n    );\n};<\/pre>\n\n\n\n<p>In the code example above, we created a state&nbsp;<code>value<\/code>, which carries a value of&nbsp;<code>1,<\/code>&nbsp;and&nbsp;<code>setValue<\/code>, which sets and updates the state&nbsp;<code>value<\/code>.<\/p>\n\n\n\n<p>To do this, we used the&nbsp;<code>useState<\/code>&nbsp;Hook and&nbsp;<code>setValue<\/code>&nbsp;to update the&nbsp;<code>value<\/code>, adding&nbsp;<code>1<\/code>&nbsp;to it every time the button is clicked. This state will then update in the React DOM, which means the page doesn\u2019t need to reload for the change to render.<\/p>\n\n\n\n<h3>Hooks<\/h3>\n\n\n\n<p><a href=\"https:\/\/blog.logrocket.com\/react-hooks-the-good-the-bad-and-the-ugly\/\">Hooks are functions that allow you to \u201chook\u201d into React features<\/a>&nbsp;like state and lifecycle functions. They are similar to decorators in Python that allow you to hook into a class or function and control its behavior.<\/p>\n\n\n\n<p>To use Hooks, you must import them from the React library. They cannot be used with class components and may only be used at the top level of a component where the function attributes are declared, as seen in the code below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React, { useState } from \"react\";\n\nfunction FavoriteColor() {\n  const [color, setColor] = useState(\"red\");\n\n  return (\n    &lt;&gt;\n      &lt;h1&gt;My favorite color is {color}!&lt;\/h1&gt;\n    &lt;\/&gt;\n  );\n}<\/pre>\n\n\n\n<p>As seen in the code above, the&nbsp;<code>useState<\/code>&nbsp;Hook is used at the top of the functional component, that is, before the return statement.<\/p>\n\n\n\n<p>Hooks make managing states easier because they were built-in to carry out simple state management logic for you, which prevents you from wasting time on reinventing the wheel.<\/p>\n\n\n\n<p>Some examples of Hooks are&nbsp;<code>useState<\/code>&nbsp;and&nbsp;<code>useEffect<\/code>.<\/p>\n\n\n\n<h3>Props<\/h3>\n\n\n\n<p>React props are similar to JavaScript function arguments and HTML attributes. They use the same syntax as HTML attributes to deliver props into a component:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;Header title=\"My react header\" \/&gt;;<\/pre>\n\n\n\n<p><a href=\"https:\/\/blog.logrocket.com\/the-beginners-guide-to-mastering-react-props-3f6f01fd7099\/\">Props are how you pass data between components<\/a>&nbsp;and can be passed down from a parent component to a child component:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function House(props) {\n  return &lt;h2&gt;I am a { props.type }!&lt;\/h2&gt;;\n}\n\nfunction Room() {\n  return (\n    &lt;&gt;\n      &lt;h1&gt;Do you know my room number?&lt;\/h1&gt;\n      &lt;House type=\"duplex\" \/&gt;\n    &lt;\/&gt;\n  );\n}<\/pre>\n\n\n\n<p>The parent component here is&nbsp;<code>Room<\/code>, while&nbsp;<code>House<\/code>&nbsp;is the child component. This is because the&nbsp;<code>House<\/code>&nbsp;component was called in the&nbsp;<code>Room<\/code>&nbsp;component, meaning a prop&nbsp;<code>type<\/code>&nbsp;was passed between them.<\/p>\n\n\n\n<h4>Passing states as props<\/h4>\n\n\n\n<p>You can also pass states as props between parent and child components:<\/p>\n\n\n\n<p>&lt;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">function House(props) {\n  return &lt;h2&gt;I am a { props.type }!&lt;\/h2&gt;;\n}\n\nfunction Room() {\n  const [type, setType] = useState(\"Duplex\");\n\n  return (\n    &lt;&gt;\n      &lt;h1&gt;Do you know my room number?&lt;\/h1&gt;\n      &lt;House type={type} setType={setType} \/&gt;\n    &lt;\/&gt;\n  );\n}<\/pre>\n\n\n\n<p>In the code example above, we declare the state&nbsp;<code>type<\/code>, which carries the value&nbsp;<code>\"Duplex\"<\/code>, and&nbsp;<code>setType<\/code>, which updates the state.<\/p>\n\n\n\n<p>Then we can pass these states to the&nbsp;<code>House<\/code>&nbsp;component as props. We also added the props argument to the&nbsp;<code>House<\/code>&nbsp;component, which collects the states already passed. Finally, we render the data in the state using&nbsp;<code>props.type<\/code>.<\/p>\n\n\n\n<h3>Redux<\/h3>\n\n\n\n<p>When working in React, you will need to handle states across components in a complicated application.&nbsp;<a href=\"https:\/\/blog.logrocket.com\/redux-isnt-dead\/\">This problem is solved by Redux<\/a>, a JavaScript package that aids in maintaining application states. Redux stores all of your states in a single source, and&nbsp;<a href=\"https:\/\/blog.logrocket.com\/why-use-redux-reasons-with-clear-examples-d21bffd5835\/\">you can learn more about it in this tutorial<\/a>.<\/p>\n\n\n\n<h3>WebPack<\/h3>\n\n\n\n<p>Webpack is a Javascript module bundler that allows you to keep dependencies as static files in your project so that you don\u2019t have to. Loaders are also included with Webpack to&nbsp;<a href=\"https:\/\/blog.logrocket.com\/versatile-webpack-configurations-react-application\/\">aid in executing certain activities inside your project<\/a>.<\/p>\n\n\n\n<h3>Server rendering<\/h3>\n\n\n\n<p>Learning server rendering will enable you to develop components on a server and render them as HTML in your browser; after all of the JavaScript modules download, React will take the stage.<\/p>\n\n\n\n<p>This is one of React\u2019s best features, and it can be utilized with any backend technology. You&nbsp;<a href=\"https:\/\/blog.logrocket.com\/why-you-should-render-react-on-the-server-side-a50507163b79\/\">can learn about server rendering in this article<\/a>.<\/p>\n\n\n\n<h2>Building the Flask and React applications<\/h2>\n\n\n\n<p>Let\u2019s now&nbsp;<a href=\"https:\/\/blog.logrocket.com\/build-deploy-flask-app-using-docker\/\">build the Flask application<\/a>&nbsp;to manage a database and data requests, which will be the backend for our React application. This section will demonstrate how to build a Python API that works with React, then build a React application that makes requests from your IT.<\/p>\n\n\n\n<h3>Flask installation<\/h3>\n\n\n\n<p>To install Flask, run the command below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">pip install flask<\/pre>\n\n\n\n<p>Next, run the following command to create the Flask project:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"># create project directory\nmkdir flaskapp\n\ncd flaskapp<\/pre>\n\n\n\n<p>We can now create an&nbsp;<code>app.py<\/code>&nbsp;to add the Python code below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from flask import Flask\n\napp = Flask(__name__)\n\n@app.route('\/ping')\ndef ping():\n    return (\"hello world\")\n\n\nif __name__ == '__main__':\n    app.run()<\/pre>\n\n\n\n<h3>Setting up the Flask application<\/h3>\n\n\n\n<p>The Flask application will require you to install&nbsp;<code>flask_sqlalchemy<\/code>&nbsp;and&nbsp;<code>flask_cors<\/code>&nbsp;using the commands below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">pip install flask_sqlalchemy \npip install flask_cors<\/pre>\n\n\n\n<p>After installing the modules needed, import them and set them up. To do this, copy the code below in your&nbsp;<code>app.py<\/code>&nbsp;file:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import os\nfrom flask import *\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\n\nfile_path = os.path.abspath(os.getcwd())+\"\\database.db\"\n \n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:\/\/\/'+file_path\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy()\ndb.init_app(app)\n\n@app.after_request\ndef after_request(response):\n  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')\n  response.headers.add('Access-Control-Allow-Credentials', 'true')\n  return response<\/pre>\n\n\n\n<p>Next, set up your database for the contact manager:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">class ContactModel(db.Model):\n    __tablename__ = \"table\"\n \n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String(), unique=True)\n \n    def __init__(self, name):\n        self.name = name\n\n    def __repr__(self):\n        return f\"{self.name}\"\n\n@app.before_first_request\ndef create_table():\n    db.create_all()<\/pre>\n\n\n\n<p>The&nbsp;<code>ContactManager<\/code>&nbsp;model creates the database tables and the&nbsp;<code>@app.before_first_request<\/code>&nbsp;decorator runs the build tables command that triggers the first time you use the Flask application.<\/p>\n\n\n\n<h4>Building the endpoints<\/h4>\n\n\n\n<p>In the code below, we can create, retrieve, and change endpoints for the contact manager application:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@app.route('\/data\/create' , methods = ['GET','POST'])\ndef create():\n    if request.method == 'GET':\n        return jsonify({\"success\": True, \"message\": \"this is the create endpoint\"}), 201\n \n    if request.method == 'POST':\n        request_data = json.loads(request.data)\n        name = request_data['name']\n        contact = ContactModel(name=name)\n        db.session.add(contact)\n        db.session.commit()\n        return jsonify({\"success\": True, \"message\": \"contact added successfully\"}), 201\n\ndef contact_serializer(contact):\n    return {'name': contact.name}\n\n@app.route('\/data')\ndef retrieveDataList():\n    return jsonify([*map(contact_serializer, ContactModel.query.all())])\n\n\n@app.route('\/data\/delete', methods=['GET','POST'])\ndef delete():\n    request_data = json.loads(request.data)\n    name = request_data['name']\n    contact = ContactModel.query.filter_by(name=name).first()\n    if request.method == 'POST':\n        if contact:\n            db.session.delete(contact)\n            db.session.commit()\n            return jsonify({\"success\": True, \"message\": \"Contact deleted successfully\"}), 201\n        abort(404)\n \n    return jsonify({\"success\": True}), 201<\/pre>\n\n\n\n<p>The&nbsp;<code>create<\/code>&nbsp;endpoint collects data under a&nbsp;<code>POST<\/code>&nbsp;request to create a contact in the database and the&nbsp;<code>retrieve<\/code>&nbsp;endpoint gets all the data stored in the database.<\/p>\n\n\n\n<p>Finally, the&nbsp;<code>delete<\/code>&nbsp;endpoint receives data under a&nbsp;<code>POST<\/code>&nbsp;request. Ensure to check if this data exists in the database before proceeding to delete it. These three endpoints will be very useful when building your React application.<\/p>\n\n\n\n<h3>Building the React application<\/h3>\n\n\n\n<p>To begin building our React applications, we must first install React:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">npm install react react-dom --save<\/pre>\n\n\n\n<p>To create your React project, enter the command below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">npx create-react-app contactmanager<\/pre>\n\n\n\n<h4>Setting up the React application<\/h4>\n\n\n\n<p>In the React application you just created, locate the&nbsp;<code>package.json<\/code>&nbsp;file and add the API URL (<a href=\"http:\/\/127.0.0.1:5000\/\">http:\/\/127.0.0.1:5000\/<\/a>) to it as seen in the code sample below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\"name\": \"contactmanager\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"proxy\":\"http:\/\/127.0.0.1:5000\/\",\n  \"dependencies\": {\n    \"@testing-library\/jest-dom\": \"^5.16.1\"\n....<\/pre>\n\n\n\n<p>Next, create two folders named&nbsp;<code>Components<\/code>&nbsp;and&nbsp;<code>Pages<\/code>. The&nbsp;<code>Components<\/code>&nbsp;folder will carry all the application components while the&nbsp;<code>Pages<\/code>&nbsp;folder will carry the page components.<\/p>\n\n\n\n<h4>The&nbsp;<code>App.js<\/code>&nbsp;file<\/h4>\n\n\n\n<p>Next, let\u2019s import and render the&nbsp;<code>ContactPage<\/code>&nbsp;component that carries all the other components for this application. Copy and paste the code in your&nbsp;<code>App.js<\/code>&nbsp;file:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import logo from '.\/logo.svg';\nimport '.\/App.css';\nimport {ContactPage} from '.\/Pages\/ContactPage';\n\nfunction App() {\n  return (\n    &lt;div className=\"App\"&gt;\n      &lt;ContactPage \/&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport default App;<\/pre>\n\n\n\n<h4>Building the components<\/h4>\n\n\n\n<p>In this section, we\u2019ll build the components that make up the contact manager application.<\/p>\n\n\n\n<h4>The&nbsp;<code>ContactPage<\/code>&nbsp;component<\/h4>\n\n\n\n<p>Create a new file called&nbsp;<code>ContactPage.js<\/code>&nbsp;in the&nbsp;<code>Pages<\/code>&nbsp;folder and copy and paste the code below into it:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React, {useState, useEffect} from 'react';\nimport {Card} from '..\/Components\/Card';\nimport {Form} from '..\/Components\/Form';\n\nexport const ContactPage = () =&gt; {\n    const [contact, setContact] = useState([])\n    const [addContact, setAddContact] = useState('')\n\n    useEffect(()=&gt; {\n        fetch('\/data').then(response =&gt; {\n            if (response.ok){\n                return response.json()\n            }\n        }).then(data =&gt; setContact(data))\n    }, [])\n\n    const handleFormChange = (inputValue) =&gt; {\n        setAddContact(inputValue)\n    }\n\n    const handleFormSubmit = () =&gt; {\n        fetch('\/data\/create', {\n            method: 'POST',\n            body: JSON.stringify({\n                name:addContact\n            }),\n            headers: {\n                \"Content-type\": \"application\/json; charset=UTF-8\"\n            }\n        }).then(response =&gt; response.json()).then(message =&gt; \n            {console.log(message);\n            getLatestContacts();\n            setAddContact('')\n            })\n        \n    }\n\n    const deleteContact = (name) =&gt; {\n        fetch('\/data\/delete', {\n            method: 'POST',\n            body: JSON.stringify({\n                name:name\n            }),\n            headers: {\n                \"Content-type\": \"application\/json; charset=UTF-8\"\n            }\n        }).then(response =&gt; response.json()).then(message =&gt; {\n            console.log(message);\n            getLatestContacts()\n            })\n        \n    }\n\n    const getLatestContacts = () =&gt; {\n        fetch('\/data').then(response =&gt; {\n            if(response.ok){\n                return response.json()\n            }\n        }).then(data =&gt; setContact(data))\n    }\n\n    \n    return (\n        &lt;&gt;\n        &lt;Form userInput={addContact} onFormChange = {handleFormChange} onFormSubmit={handleFormSubmit}\/&gt;\n        &lt;Card listOfContacts={contact} onDelete={deleteContact}\/&gt;\n        &lt;\/&gt;\n    )\n}<\/pre>\n\n\n\n<p>In the code above, we created the&nbsp;<code>ContactPage<\/code>&nbsp;component and rendered the&nbsp;<code>Card<\/code>&nbsp;and&nbsp;<code>Form<\/code>&nbsp;components in it.<\/p>\n\n\n\n<p>Then, by creating a&nbsp;<code>contact<\/code>&nbsp;state and its setter,&nbsp;<code>setContact<\/code>, this will carry the contacts\u2019 data. The&nbsp;<code>addContact<\/code>&nbsp;state and its setter,&nbsp;<code>setAddContact<\/code>, also carry the input for the data to add to the database.<\/p>\n\n\n\n<p>Next, the&nbsp;<code>useEffect<\/code>&nbsp;Hook and the&nbsp;<code>fetch<\/code>&nbsp;method to retrieve data from the&nbsp;<code>\/data<\/code>&nbsp;endpoint in the Flask application, setting the retrieved data to the current&nbsp;<code>contact<\/code>&nbsp;state. This ensures the retrieved data is the same as the data displayed on the application.<\/p>\n\n\n\n<p>When creating a&nbsp;<code>handleFormChange<\/code>&nbsp;function, it sets the state of the&nbsp;<code>addContact<\/code>&nbsp;state to the current data in the input field. We can then pass&nbsp;<code>handleFormChange<\/code>&nbsp;as a prop to the&nbsp;<code>Form<\/code>&nbsp;component.<\/p>\n\n\n\n<p>Next, the&nbsp;<code>handleFormSubmit<\/code>&nbsp;function sends data to the&nbsp;<code>create<\/code>&nbsp;endpoint in Flask to add new data to the database and clear the input field by setting the&nbsp;<code>setAddContact<\/code>&nbsp;state to an empty string while getting the latest data after the creation of the new contact using the&nbsp;<code>getLatestContacts<\/code>&nbsp;function.<\/p>\n\n\n\n<p>This function also sets the&nbsp;<code>contact<\/code>&nbsp;state to the most current data after using the&nbsp;<code>fetch<\/code>&nbsp;method to retrieve data. We can then pass&nbsp;<code>handleFormSubmit<\/code>&nbsp;as a prop to the&nbsp;<code>Form<\/code>&nbsp;component.<\/p>\n\n\n\n<p>And finally, the&nbsp;<code>deleteContact<\/code>&nbsp;function deletes contacts from the Flask database by making a request using the&nbsp;<code>fetch<\/code>&nbsp;method to the&nbsp;<code>data\/<strong>delete<\/strong><\/code>&nbsp;endpoint, followed by the&nbsp;<code>getLatestContacts<\/code>&nbsp;function to get the new data after the delete action.<\/p>\n\n\n\n<p>We can then pass the&nbsp;<code>deleteContact<\/code>&nbsp;function and the&nbsp;<code>contact<\/code>&nbsp;state to the&nbsp;<code>Card<\/code>&nbsp;component.<\/p>\n\n\n\n<h4>The&nbsp;<code>Card<\/code>&nbsp;component<\/h4>\n\n\n\n<p>The&nbsp;<code>Card<\/code>&nbsp;component renders all the data retrieved from the Flask application database. To use the&nbsp;<code>Card<\/code>&nbsp;component, create a new file called&nbsp;<code>Card.js<\/code>&nbsp;in the components folder and copy and paste the code below into it:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react';\n\nexport const Card = ({ listOfContacts, onDelete }) =&gt; {\n    \n    const handleDelete = (name) =&gt; {\n        onDelete(name);\n    }\n\n    return(\n        &lt;&gt;\n        &lt;h2&gt;Contact List&lt;\/h2&gt;\n        {listOfContacts.map(contact =&gt; {\n            return(\n                &lt;ul key={contact.name}&gt;\n                    &lt;li&gt;\n                        {contact.name}  \n                     &lt;button onClick={() =&gt; handleDelete(contact.name)}&gt; x &lt;\/button&gt;\n                    &lt;\/li&gt;\n                &lt;\/ul&gt;\n            )\n        })}\n        &lt;\/&gt;\n    ) \n}<\/pre>\n\n\n\n<p>By rendering each contact in a list using the map function to map the data in the&nbsp;<code>listOfContact<\/code>&nbsp;prop passed from the&nbsp;<code>ContactPage<\/code>, we can add a delete button to trigger the&nbsp;<code>handleDelete<\/code>&nbsp;function and pass the name of the particular contact to be deleted.<\/p>\n\n\n\n<p>The&nbsp;<code>handleDelete<\/code>&nbsp;function then collects the name passed and calls the&nbsp;<code>onDelete<\/code>&nbsp;prop that was passed from the&nbsp;<code>ContactPage<\/code>&nbsp;component and carries out the same function as&nbsp;<code>deleteContact<\/code>.<\/p>\n\n\n\n<p>With that, our contact list currently looks like the list below:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/contact-list.png\" alt=\"Contact List Showing Two Names With Xs Next To Them\" class=\"wp-image-88133\"\/><\/figure><\/div>\n\n\n\n<h4>The&nbsp;<code>Form<\/code>&nbsp;component<\/h4>\n\n\n\n<p>The&nbsp;<a href=\"https:\/\/blog.logrocket.com\/guide-react-forms-events-formik\/\">form component renders the form<\/a>&nbsp;used to submit data to our application. To do this, create a new file called&nbsp;<code>Form.js<\/code>&nbsp;in the&nbsp;<code>Components<\/code>&nbsp;folder and copy and paste the code below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react';\n\nexport const Form = ({ userInput, onFormChange, onFormSubmit }) =&gt; {\n\n    const handleChange = (event) =&gt; {\n        onFormChange(event.target.value);\n    }\n\n    const handleSubmit = (event) =&gt; {\n        event.preventDefault()\n        onFormSubmit()\n    }\n\n    return(\n        &lt;&gt;\n        &lt;h2&gt;Add Contact&lt;\/h2&gt;\n        &lt;form onSubmit={handleSubmit}&gt;\n            &lt;input type=\"text\" required value={userInput} onChange={handleChange}&gt;&lt;\/input&gt;\n            &lt;input type=\"submit\" &gt;&lt;\/input&gt;\n        &lt;\/form&gt;\n        &lt;\/&gt;\n    )\n}<\/pre>\n\n\n\n<p>Here, the&nbsp;<code>handleSubmit<\/code>&nbsp;function is attached to the form, while the&nbsp;<code>handleChange<\/code>&nbsp;function is attached to the name input element.<\/p>\n\n\n\n<p>The&nbsp;<code>handleChange<\/code>&nbsp;function triggers when we enter data into the HTML text input field, while the&nbsp;<code>handleSubmit<\/code>&nbsp;function triggers when the form is submitted. This is done by calling the prop functions passed from the&nbsp;<code>ContactPage<\/code>&nbsp;in&nbsp;<code>handleChange<\/code>&nbsp;and&nbsp;<code>handleSubmit<\/code>.<\/p>\n\n\n\n<p>In&nbsp;<code>handleChange<\/code>, we called the&nbsp;<code>onFormChange.<\/code>&nbsp;prop, which performs the&nbsp;<code>handleFormChange<\/code>&nbsp;function in the&nbsp;<code>ContactPage<\/code>&nbsp;component, while in&nbsp;<code>handleSubmit<\/code>, we called the&nbsp;<code>onFormChange.<\/code>&nbsp;prop to perform the&nbsp;<code>handleFormSubmit<\/code>&nbsp;function.<\/p>\n\n\n\n<p>And here\u2019s the final Add Contact form:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/Add-contact-field.png\" alt=\"Add Contact Field With Submit Button\" class=\"wp-image-88136\"\/><\/figure><\/div>\n\n\n\n<h2>Conclusion<\/h2>\n\n\n\n<p>Finally, we have a working contact list that we can effectively add and delete contacts:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/01\/Final-contact-app-1.gif\" alt=\"Final Contact App Showing Adding And Deleting Contacts\" class=\"wp-image-88322\"\/><\/figure><\/div>\n\n\n\n<p>Both Python and React are excellent choices for creating a web application. When utilizing them, you\u2019ll notice that several features, such as Python\u2019s decorators and React Hooks, are identical.<\/p>\n\n\n\n<p>Only a few changes in code syntax and data model\/transfer principles exist, such as how functions are defined and how data in a React component is managed differently than data in a Python class.<\/p>\n\n\n\n<p>As a Python developer, learning React is important when building the server-side of your web applications. Thanks for reading, and happy coding!!<\/p>\n\n\n\n<h2>Full visibility into production React apps<\/h2>\n\n\n\n<p>Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you\u2019re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time,&nbsp;<a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\">try LogRocket<\/a>.&nbsp;<a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\">LogRocket<\/a>&nbsp;is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app&#8217;s performance, reporting with metrics like client CPU load, client memory usage, and more.<\/p>\n\n\n\n<p>The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.<\/p>\n\n\n\n<p>Modernize how you debug your React apps \u2014&nbsp;<a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\">start monitoring for free<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Although the most popular JavaScript library for creating user interfaces is React, learning how to use this library as a Python developer can be a long and tough process.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[126,30],"tags":[127,65],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2210"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2210"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2210\/revisions"}],"predecessor-version":[{"id":2211,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2210\/revisions\/2211"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2210"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2210"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2210"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}