Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Entrepreneurship

    Strategic Approaches to Navigating Entrepreneurship Competition

    JavaScript

    Introduction to Micro Frontends: The New Tech on the Block

    Programming

    RxJS Methods. Part2

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, January 21
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / React / React Lessons / React Lesson 12: Checking Homework Progress from Lesson 11
    JavaScript

    React Lesson 12: Checking Homework Progress from Lesson 11

    Mohammad Shad MirzaBy Mohammad Shad MirzaJune 23, 2020Updated:July 2, 2020No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    React Lesson 12: Checking Homework Progress from Lesson 11
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    React Lesson 12: Checking Homework Progress from Lesson 11
    React Lesson 12: Checking Homework Progress from Lesson 11

    Hey everyone, In this lesson, we will go through our home task for the Lesson 11 and learn how it is effective to connect the store to any component. Our home task was to create a form that takes input and add a comment. Let’s start.

    Step 1: Create a form that takes user input

    Let’s go to the component directory and add a CommentForm.js file. This file will include a form with text input and a button to add a comment. We will pass the addComment function and articleId from parent component. We will see that in a minute.

    import React, { Component } from "react";
    import PropTypes from "prop-types";
    
    class CommentForm extends Component {
      static propTypes = {
        addComment: PropTypes.func.isRequired,
        articleId: PropTypes.string.isRequired
      };
    
      state = {
        user: "",
        text: ""
      };
    
      handleSubmit = e => {
        const { addComment, articleId } = this.props;
        e.preventDefault();
        addComment(this.state, articleId);
        this.setState({
          user: "",
          text: ""
        });
      };
    
      render() {
        const { text, user } = this.state;
        return (
          <form onSubmit={this.handleSubmit}>
            <label>Comment:</label>
            <input
              value={text}
              onChange={e => this.setState({ text: e.target.value })}
            />
            <label>By:</label>
            <input
              value={user}
              onChange={e => this.setState({ user: e.target.value })}
            />
            <button type="submit">Add comment</button>
          </form>
        );
      }
    }
    
    export default CommentForm;

    How does the form work?

    Let’s go into further details of how the form is working. You can see that we are storing user and text info in the store. Whenever the user types something in input, we take change via onChangehandler and update the state using setState. This state is being passed as the value of input which we can use later.

    <input
        value={text}
        onChange={e => this.setState({ text: e.target.value })}
    />

    When the user hits the submit button, we call handleSubmit function which takes the values from the state and dispatches an action to addComment. It then resets the state back to its default state.

    this.setState({
        user: "",
        text: ""
    });

    Step 2: Include form in CommentList component

    The next step is to add this form in the CommentList component where the user will type and add comments. But first, we will restructure our project. CommentList will be connected to the store now because it will contain the form. Let’s move it to /containers directory and correct the import paths. After that, let’s import the CommentForm we just created and use it. I have added comments to you about what we are updating.

    import React, { Component } from "react";
    import Comment from "./../components/Comment"; //update import
    import CommentForm from "./../components/CommentForm"; //import CommentForm
    import toggleOpen from "../decorators/toggleOpen";
    import { addComment } from "../actions"; // action creator that we will create next
    import { connect } from "react-redux";
    
    @toggleOpen
    class CommentList extends Component {
    
      render() {
        // get article from props passed via parent component
        const { commentObj, isOpen, toggleOpen, article, addComment } = this.props;
        
        if (!commentObj || !commentObj.length) return <h3>no comment yet</h3>;
    
        const commentItems = commentObj.map(comment => (
          <li key={comment.id}>
            <Comment comment={comment} />
          </li>
        ));
    
        // update body and add CommentForm
        const body = isOpen ? (
          <div>
            <ul>{commentItems}</ul>
            <CommentForm articleId={article.id} addComment={addComment} />
          </div>
        ) : null;
    
        const linkText = isOpen ? "close comment" : "show comments";
        return (
          <div>
            <button onClick={toggleOpen} ref="toggler">
              {linkText}
            </button>
            {body}
          </div>
        );
      }
    }
    
    const mapStateToProps = (state, props) => {
      console.log({ props, state });
      return {
        commentObj: props.comments.map(id => state.comments.comments.get(id))
      };
    };
    
    export default connect(
      mapStateToProps,
      { addComment }
    )(CommentList);

    Step 3: Create addComment action

    Read More:  Tempor Nec Feugiat Nislpretium Fusce Platea Dictumst

    Let’s quickly add a type for action creator and add an action that takes user and comment id then updates the store. Go to /types.js and add the following line:

    export const ADD_COMMENT = "add_comment";

    Now go to /actions directory and add a new file comments.js

    import { ADD_COMMENT } from "../types";
    
    export const addComment = (comment, articleId) => {
      return {
        type: ADD_COMMENT,
        payload: { ...comment, articleId },
        withRandomId: true
      };
    }

    export this action from root file actions/index.js

    //other exports
    export * from "./comments";

    We are passing withRandomId: true to generate a random id whenever this action is called. We can easily do this by adding a middle where that performs this task for us.

    Adding middleware to generate a random id for comments

    Go to /middlewares directory and add a file randomID.js

    export default store => next => action => {
      const { withRandomId, ...rest } = action;
      if (!withRandomId) return next(action); // if withRandom is false, continue as usual
    
      next({
        ...rest,
        randomId: Date.now() + Math.random() // generate and append random id with the rest of the payload if withRandom is true
      });
    };

    Now, add this in store

    //...imports
    import randomId from "../middlewares/randomID"; //import randomID middleware
    
    const enhancer = compose(
      applyMiddleware(dumbMiddleware, logger, randomId), // apply middleware
      window.devToolsExtension ? window.devToolsExtension() : f => f
    );
    
    const store = createStore(reducer, {}, enhancer);
    
    export default store;

    We are good to go now 👍🏼

    Step 4: Update reducer to add comments

    Go to reducers/article.js and add a switch case for addComment action.

    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case ADD_COMMENT:
          return {
            ...state, comments: state.comments.set(
              action.randomId,
              new Comment({
                id: action.randomId,
                user: action.payload.user,
                text: action.payload.text,
              })
            )}
        default:
          return state;
      }
    };

    And the last thing. Take a look at reducer/articles.js, in particular at Record :

    const Article = Record({
        "id": "",
        "date": "",
        "title": "",
        "text": "",
        "comments": []
    });

    It is an immutable structure. And while you won’t do anything with the primitives, it is quite possible to do with comments. For example, by using push for comments you mutate them with this method since it is a simple array. With this action, you lose everything that immutable structures bring to you. When you change something inside, Immutable.js thinks nothing has really changed. So we have to take care of that.

    Read More:  React Lesson 4: Homework. Decorators and Mixins

    Let’s also update the article.js reducer to return updated comments list.

    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case ADD_COMMENT:
          return {
            ...state, articles: state.articles.updateIn(
              [action.payload.articleId, "comments"],
              comments => comments.concat(action.randomId)
            )};
        case DELETE_ARTICLE:
          return { ...state, articles: state.articles.delete(action.payload) };
    
        default:
          return state;
      }
    };

    Now we have to do is pass the article to the CommentList component. Go to components/Article/index.js and pass the article:

    //...
    <section>
        {text} <CommentList article={article} comments={comments} />
    </section>
    //...

    We are done with your home task. One thing can do in add a helper in component/Article.js comment that filters data and connect it with the store.

    const mapStateToProps = state => {
      return {
        articles: filterArticles(state.article.articles, state.filters)
      };
    };
    
    export default connect(
      mapStateToProps,
      {}
    )(Articles);

    Here, filterArticle is a helper function that filters our data and makes our component “smart” in choosing when to re-render. Let’s quickly write that helper:

    function filterArticles(articles, { from, to, selectedArticles }) {
      return articles
        .valueSeq()
        .filter(article =>
          selectedArticles.length ? selectedArticles.includes(article.id) : true
        )
        .filter(
          article =>
            (!from || Date.parse(article.date) > from) &&
            (!to || Date.parse(article.date) < to)
        );
    }

    Redux will check whether the list of filtered articles corresponds to the previous one and will conclude that nothing needs to be updated. That’s why we add connect whenever we need to refer to the data we lack at the moment. We need to choose: to take the data at a higher level or add connect at a lower level.

    That’s it for today’s lesson. I hope you understand how to work forms and use connect function better. Carefully learn and analyze everything we’ve done in frames of your home task and we will move on. Good luck, see you later!

    You can visit the codesandbox below to see Lesson 12 in action.
    Edit React_lesson_lesson12
    The lesson code is available in our repository.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Streamlining Resource Allocation for Enhanced Project Success

    December 18, 2024

    Conducting Effective Post-Project Evaluations: A Guide

    December 16, 2024

    Strategies for Keeping Projects on Track and Meeting Deadlines

    December 10, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript June 27, 2019

    Introduction to Micro Frontends: The New Tech on the Block

    Like with all powerful technologies, micro frontends often cause confusion among developers, as evidenced by the ever so popular search queries like “What are micro frontends?” It may be tempting to try and ignore it, but then you’ll be missing out on the amazing opportunities that micro frontends provide — after all, they’re not just a hip trend to follow. In this article, we’ll explore what micro frontends are, what benefits they can bring, how they can be used, and what caveats and pitfalls they pose.

    Create a Simple POS with React, Node and MongoDB #0: Initial Setup Frontend and Backend

    January 7, 2020

    Важность учета рабочего времени

    June 25, 2016

    Exploring the Power of JavaScript Proxies and Reflect API

    April 22, 2023

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Strategic LinkedIn Tactics for E-Commerce Lead Generation

    LinkedIn November 28, 2024

    Using SWR for Efficient Data Fetching in Next.js Applications

    JavaScript April 11, 2023

    Analyzing Storytelling’s Impact on Content Marketing Effectiveness

    Content & Leadership August 27, 2025

    Strategies for Effectively Managing Software Project Deadlines

    Development November 28, 2024

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Interview

    Essential Strategies for Effective Technical Interview Preparation

    Programming

    14. Node.js Lessons. Script Debugging pt 1.

    GraphQL

    How To Build a Github Jobs App using React, Apollo, and GraphQL – Part #1: Build the GraphQL Server

    Most Popular

    Imposter Syndrome in Web Development: Understand It, Overcome It

    Job

    Search of Investments

    Comics

    Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

    JavaScript
    © 2026 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.