Convert Figma logo to code with AI

gothinkster logoreact-redux-realworld-example-app

Exemplary real world application built with React + Redux

5,569
2,511
5,569
87

Top Related Projects

80,429

"The mother of all demo apps" — Exemplary fullstack Medium.com clone powered by React, Angular, Node, Django, and many more

Exemplary real world application built with Angular

An exemplary real-world application built with Vue.js, Vuex, axios and different other technologies. This is a good example to discover Vue for beginners.

ASP.NET Core backend implementation for RealWorld

Quick Overview

The gothinkster/react-redux-realworld-example-app is a comprehensive example application showcasing the implementation of a real-world app using React and Redux. It serves as a reference for developers looking to build scalable and maintainable web applications with these technologies. The project follows best practices and demonstrates how to structure a complex React-Redux application.

Pros

  • Provides a complete, production-ready example of a React-Redux application
  • Implements real-world features like authentication, CRUD operations, and routing
  • Follows best practices for state management and component structure
  • Serves as an excellent learning resource for developers new to React and Redux

Cons

  • May be overwhelming for beginners due to its complexity
  • Some dependencies and practices might become outdated over time
  • Lacks extensive documentation on the codebase structure and design decisions
  • May not cover all edge cases or advanced scenarios in a real-world application

Code Examples

  1. Redux action creator:
export const login = (email, password) => {
  return dispatch => {
    dispatch({ type: LOGIN });
    return agent.Auth.login(email, password)
      .then(({ user }) => dispatch({ type: LOGIN_SUCCESS, payload: user }))
      .catch(error => dispatch({ type: LOGIN_FAILURE, error }));
  };
};

This code defines a Redux action creator for user login, handling asynchronous API calls and dispatching appropriate actions based on the result.

  1. React component with Redux connection:
import React from 'react';
import { connect } from 'react-redux';
import { logout } from './authActions';

const Header = ({ currentUser, logout }) => (
  <nav>
    {currentUser ? (
      <button onClick={logout}>Log out</button>
    ) : (
      <a href="/login">Log in</a>
    )}
  </nav>
);

const mapStateToProps = state => ({
  currentUser: state.auth.currentUser
});

export default connect(mapStateToProps, { logout })(Header);

This example shows a React component connected to the Redux store, accessing the current user state and dispatching the logout action.

  1. Redux reducer:
const initialState = {
  articles: [],
  articlesCount: 0,
  currentPage: 0
};

export default (state = initialState, action) => {
  switch (action.type) {
    case ARTICLE_LIST_LOADED:
      return {
        ...state,
        articles: action.payload.articles,
        articlesCount: action.payload.articlesCount,
        currentPage: action.page
      };
    default:
      return state;
  }
};

This code demonstrates a Redux reducer handling the ARTICLE_LIST_LOADED action, updating the state with new article data.

Getting Started

To run the project locally:

  1. Clone the repository:

    git clone https://github.com/gothinkster/react-redux-realworld-example-app.git
    
  2. Install dependencies:

    cd react-redux-realworld-example-app
    npm install
    
  3. Start the development server:

    npm start
    
  4. Open your browser and navigate to http://localhost:3000 to view the app.

Competitor Comparisons

80,429

"The mother of all demo apps" — Exemplary fullstack Medium.com clone powered by React, Angular, Node, Django, and many more

Pros of realworld

  • Comprehensive collection of example apps in various frameworks and languages
  • Serves as a learning resource for multiple tech stacks
  • Provides a standardized, real-world application structure across different implementations

Cons of realworld

  • May be overwhelming for beginners due to the large number of implementations
  • Requires more time to navigate and find specific examples
  • Potentially less focused on in-depth React and Redux specifics

Code Comparison

react-redux-realworld-example-app:

import { createStore, applyMiddleware, combineReducers } from 'redux';
import { promiseMiddleware, localStorageMiddleware } from './middleware';
import auth from './reducers/auth';
import common from './reducers/common';
import home from './reducers/home';

realworld:

// No direct code comparison available as realworld is a collection of implementations
// Each implementation may have its own structure and code organization

The react-redux-realworld-example-app provides a specific React and Redux implementation, while realworld offers a broader range of examples across different frameworks and languages. The former is more focused and potentially easier for React developers to dive into, while the latter provides a wider perspective on building real-world applications using various technologies.

Exemplary real world application built with Angular

Pros of angular-realworld-example-app

  • Built with Angular, offering a robust framework with strong typing and dependency injection
  • Utilizes RxJS for reactive programming, enhancing state management and asynchronous operations
  • Follows Angular's modular architecture, promoting better code organization and reusability

Cons of angular-realworld-example-app

  • Steeper learning curve compared to React, especially for developers new to TypeScript
  • More opinionated structure, which may limit flexibility in certain scenarios
  • Potentially larger bundle size due to Angular's comprehensive feature set

Code Comparison

angular-realworld-example-app:

@Component({
  selector: 'app-article-list',
  templateUrl: './article-list.component.html'
})
export class ArticleListComponent implements OnInit {
  constructor(private articlesService: ArticlesService) {}
  ngOnInit() {
    this.articlesService.getArticles().subscribe(articles => {
      // Handle articles
    });
  }
}

react-redux-realworld-example-app:

const ArticleList = () => {
  const dispatch = useDispatch();
  const articles = useSelector(state => state.articles);
  
  useEffect(() => {
    dispatch(fetchArticles());
  }, [dispatch]);

  return (
    // Render articles
  );
};

The Angular example uses dependency injection and RxJS observables, while the React example utilizes hooks and Redux for state management. Angular's approach is more structured, while React's is more flexible and functional.

An exemplary real-world application built with Vue.js, Vuex, axios and different other technologies. This is a good example to discover Vue for beginners.

Pros of vue-realworld-example-app

  • Simpler state management with Vue's built-in reactivity system
  • More concise and readable code due to Vue's template syntax
  • Easier learning curve for developers new to frontend frameworks

Cons of vue-realworld-example-app

  • Smaller ecosystem and community compared to React and Redux
  • Less flexibility for complex state management scenarios
  • Fewer job opportunities in the market compared to React

Code Comparison

vue-realworld-example-app:

<template>
  <div class="article-meta">
    <a href=""><img :src="article.author.image" /></a>
    <div class="info">
      <a href="" class="author">{{ article.author.username }}</a>
      <span class="date">{{ article.createdAt | date }}</span>
    </div>
    <button class="btn btn-sm btn-outline-secondary">
      <i class="ion-plus-round"></i>
      &nbsp;
      Follow {{ article.author.username }}
    </button>
  </div>
</template>

react-redux-realworld-example-app:

const ArticleMeta = ({ article }) => {
  return (
    <div className="article-meta">
      <Link to={`/@${article.author.username}`}>
        <img src={article.author.image} alt={article.author.username} />
      </Link>
      <div className="info">
        <Link to={`/@${article.author.username}`} className="author">
          {article.author.username}
        </Link>
        <span className="date">
          {new Date(article.createdAt).toDateString()}
        </span>
      </div>
      <ArticleActions article={article} />
    </div>
  );
};

Pros of node-express-realworld-example-app

  • Backend-focused, providing a robust API implementation
  • Simpler architecture, easier to understand for backend developers
  • Better suited for microservices and scalable backend systems

Cons of node-express-realworld-example-app

  • Lacks frontend implementation, requiring additional work for a complete application
  • May require more setup for developers primarily focused on frontend development
  • Less comprehensive for full-stack JavaScript developers

Code Comparison

node-express-realworld-example-app:

router.post('/users', function(req, res, next){
  var user = new User();

  user.username = req.body.user.username;
  user.email = req.body.user.email;
  user.setPassword(req.body.user.password);

  user.save().then(function(){
    return res.json({user: user.toAuthJSON()});
  }).catch(next);
});

react-redux-realworld-example-app:

export default connect(mapStateToProps, mapDispatchToProps)(React.memo(Register));

function Register(props) {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const submitForm = (username, email, password) => ev => {
    ev.preventDefault();
    props.onSubmit(username, email, password);
  };

The node-express example focuses on server-side user creation, while the react-redux example demonstrates client-side form handling and state management. This highlights the different focuses of the two repositories, with node-express handling backend logic and react-redux managing frontend interactions.

ASP.NET Core backend implementation for RealWorld

Pros of aspnetcore-realworld-example-app

  • Built with ASP.NET Core, offering better performance and cross-platform compatibility
  • Utilizes Entity Framework Core for efficient database operations
  • Implements a clean architecture pattern, promoting separation of concerns

Cons of aspnetcore-realworld-example-app

  • Less frontend flexibility compared to the React-Redux implementation
  • Steeper learning curve for developers not familiar with .NET ecosystem
  • Limited hot-reloading capabilities during development

Code Comparison

react-redux-realworld-example-app (Redux action):

export const ARTICLE_PAGE_LOADED = 'ARTICLE_PAGE_LOADED';
export const ARTICLE_PAGE_UNLOADED = 'ARTICLE_PAGE_UNLOADED';

export function articlePageLoaded(payload) {
  return { type: ARTICLE_PAGE_LOADED, payload };
}

aspnetcore-realworld-example-app (Controller action):

[HttpGet]
public async Task<IActionResult> Get([FromQuery] string slug)
{
    var article = await _articleRepository.GetArticleAsync(slug);
    return Ok(article);
}

The React-Redux example uses actions and reducers for state management, while the ASP.NET Core example utilizes controller actions and dependency injection. The ASP.NET Core implementation provides a more structured backend approach, whereas the React-Redux version offers greater frontend flexibility and component-based architecture.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

React + Redux Example App

RealWorld Frontend

React + Redux codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld spec and API.

  

Demo    RealWorld

Originally created for this GH issue. The codebase is now feature complete; please submit bug fixes via pull requests & feedback via issues.

We also have notes in our wiki about how the various patterns used in this codebase and how they work (thanks @thejmazz!)

Getting started

You can view a live demo over at https://react-redux.realworld.io/

To get the frontend running locally:

  • Clone this repo
  • npm install to install all req'd dependencies
  • npm start to start the local server (this project uses create-react-app)

Local web server will use port 4100 instead of standard React's port 3000 to prevent conflicts with some backends like Node or Rails. You can configure port in scripts section of package.json: we use cross-env to set environment variable PORT for React scripts, this is Windows-compatible way of setting environment variables.

Alternatively, you can add .env file in the root folder of project to set environment variables (use PORT to change webserver's port). This file will be ignored by git, so it is suitable for API keys and other sensitive stuff. Refer to dotenv and React documentation for more details. Also, please remove setting variable via script section of package.json - dotenv never override variables if they are already set.

Making requests to the backend API

For convenience, we have a live API server running at https://conduit.productionready.io/api for the application to make requests against. You can view the API spec here which contains all routes & responses for the server.

The source code for the backend server (available for Node, Rails and Django) can be found in the main RealWorld repo.

If you want to change the API URL to a local server, simply edit src/agent.js and change API_ROOT to the local server's URL (i.e. http://localhost:3000/api)

Functionality overview

The example application is a social blogging site (i.e. a Medium.com clone) called "Conduit". It uses a custom API for all requests, including authentication. You can view a live demo over at https://redux.productionready.io/

General functionality:

  • Authenticate users via JWT (login/signup pages + logout button on settings page)
  • CRU* users (sign up & settings page - no deleting required)
  • CRUD Articles
  • CR*D Comments on articles (no updating required)
  • GET and display paginated lists of articles
  • Favorite articles
  • Follow other users

The general page breakdown looks like this:

  • Home page (URL: /#/ )
    • List of tags
    • List of articles pulled from either Feed, Global, or by Tag
    • Pagination for list of articles
  • Sign in/Sign up pages (URL: /#/login, /#/register )
    • Use JWT (store the token in localStorage)
  • Settings page (URL: /#/settings )
  • Editor page to create/edit articles (URL: /#/editor, /#/editor/article-slug-here )
  • Article page (URL: /#/article/article-slug-here )
    • Delete article button (only shown to article's author)
    • Render markdown from server client side
    • Comments section at bottom of page
    • Delete comment button (only shown to comment's author)
  • Profile page (URL: /#/@username, /#/@username/favorites )
    • Show basic user info
    • List of articles populated from author's created articles or author's favorited articles

Brought to you by Thinkster