English 中文(简体)
RxJS - Working with RxJS & ReactJS
  • 时间:2024-12-22

Working with RxJS & ReactJS


Previous Page Next Page  

In this chapter, we will see how to use RxJs with ReactJS. We will not get into the installation process for Reactjs here, to know about ReactJS Installation refer this pnk: /reactjs/reactjs_environment_setup.htm

Example

We will directly work on an example below, where will use Ajax from RxJS to load data.

index.js


import React, { Component } from "react";
import ReactDOM from "react-dom";
import { ajax } from  rxjs/ajax ;
import { map } from  rxjs/operators ;
class App extends Component {
   constructor() {
      super();
      this.state = { data: [] };
   }
   componentDidMount() {
      const response = ajax( https://jsonplaceholder.typicode.com/users ).pipe(map(e => e.response));
      response.subscribe(res => {
         this.setState({ data: res });
      });
   }
   render() {
      return (
         <span>
            <h3>Using RxJS with ReactJS</h3>
            <ul>
               {this.state.data.map(el => (
                  <p>
                     {el.id}: {el.name}
                  </p>
               ))}
            </ul>
         </span>
      );
   }
}
ReactDOM.render(<App />, document.getElementById("root"));

index.html


<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8" />
      <title>ReactJS Demo</title>
   <head>
   <body>
      <span id = "root"></span>
   </body>
</html>

We have used ajax from RxJS that will load data from this Url − https://jsonplaceholder.typicode.com/users.

When you compile, the display is as shown below −

RxJs with ReactJS Advertisements