1

I have created a student feedback app at the first page of the app i am taking student info and after student submitting all details in the form successfully the user will be redirected to the feedback page,in the feedback page they will get some multiple choice questions and then to some more questions(few questions for better response). And after these steps user will get a Thank You message for their feedback and the name of the user should be the name they had entered in the first form.

here is my Student Feedback code.

import React, { Component } from 'react';
import { Button, Container, Form, Row } from 'react-bootstrap';
import vector from '../../images/01.png';
import Navbar from '../layout/Navbar';
import { connect } from "react-redux";
import { createStudent } from '../../store/actions/studentActions';
import ThankYou from './ThankYou';

const validIDRegex = RegExp(/^[A-Z][A-Z]\/[A-Z][A-Z]\/[A-Z][A-Z]\/[\d]{2}-[\d]{2}\/[\d]{2}$/i);

const validEmailRegex = RegExp(
  /^((?!\.)[\w-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/gm
);
const validPhoneRegex = RegExp(/^\d{10}$/);
const validStringRegex = RegExp(/\d/);

class StudentDetails extends Component{
    constructor() {
        super();
        this.state = {
            id: "",
        course: "",
        name: "",
        phone:"",
        email: "",
        errors: {
         id: "",
        course: "",
        name: "",
        phone:"",
        email: "",
      }
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleChange = (event) => {
        event.preventDefault();
        this.setState(
            {
                [event.target.name]: event.target.value,
            }
        );
        let { name, value } = event.target;
        let errors = this.state.errors;

        switch (name) {
            case 'id':
                errors.id =
                    // value.length < 17
                    validIDRegex.test(value)
                        ? ''
                        : 'Invalid ID';
                break;
            case 'course':
                errors.course =
                    validStringRegex.test(value)
                        ? 'Invalid Course'
                        : '';
                break;
            case 'name':
                errors.name =
                    validStringRegex.test(value)
                        ? 'Invalid Name'
                        : '';
                break;
            case 'phone':
                errors.phone =
                    validPhoneRegex.test(value)
                        ? ''
                        : 'Invalid Phone No.';
                break;
            case 'email':
                errors.email =
                    validEmailRegex.test(value)
                        ? ''
                        : 'Invalid Email';
                break;
            default:
                break;
        }
    }



    handleSubmit(e) {
        e.preventDefault();
        let errors = this.state.errors;
        console.log(this.state);
        if (errors.id === "") {
            if (errors.name === "") {
                if (errors.course === "") {
                    if ( errors.phone === "" ) {
                        if (errors.email === "") {                            
                            this.props.createStudent(this.state);
                            this.props.history.push("/feedback");
                        }
                    }
                }
            }
        }
    }

     componentDidMount(){
        this.nameInput.focus();
    }
    render() {
        const {errors} = this.state;
        return (
        <>
        <Navbar />
        <Container fluid className="body-bg">
            <Row className="row">
                    <div className="center">
                        <h4 className="heading">Lets Make Our Training Better</h4>
                        <p>Be Expressive, Be Honest</p>
                    </div>
                <Container>
                   <section className="main" sm={12}>
                    <div className="form_div" sm={12} md={8}>
                        <Form onSubmit={this.handleSubmit} id="myForm">
                             <div className="form-group">
                                <div className="error-div">
                                <label className="label">Your Student ID</label>
                                {errors.id.length > 0 && 
                                    <span className='error'>{errors.id}</span>}
                               </div>
                                <input type="text" maxLength="17" name="id" ref={(input) => { this.nameInput = input; }}  value={this.state.id} onChange={this.handleChange} className="form-control" placeholder="AD/RH/WM/08-19/27" required/>
                                <p>You can check this on your i-card or contact us please.</p>
                            </div>
                            <div className="form-group">                                
                                <div className="error-div">
                                    <label className="label">Your Course</label>
                                    {errors.course.length > 0 && 
                                    <span className='error'>{errors.course}</span>}
                                </div>
                                <input type="text"  className="form-control" name="course" value={this.state.course} onChange={this.handleChange} required/>
                            </div>
                            <div className="form-group">                                
                                <div className="error-div">
                                    <label className="label">Your Name</label>
                                    {errors.name.length > 0 && 
                                    <span className='error'>{errors.name}</span>}
                                </div>
                                <input type="text"  className="form-control" name="name" value={this.state.name} onChange={this.handleChange} required/>
                            </div>
                            <div className="form-group">                                
                                <div className="error-div">
                                    <label className="label">Your Mobile No.</label>
                                    {errors.phone.length > 0 && 
                                    <span className='error'>{errors.phone}</span>}
                                </div>
                                <input type="text" maxLength="10" className="form-control" name="phone" value={this.state.phone} onChange={this.handleChange} required/>
                            </div>
                             <div className="form-group">
                                <div className="error-div">
                                    <label className="label">Your Email Address</label>
                                    {errors.email.length > 0 && 
                                    <span className='error'>{errors.email}</span>}
                                </div>
                                <input type="email"  className="form-control" name="email" value={this.state.email} onChange={this.handleChange} required/>
                                </div>
                            <div className="btn-grp">
                                <Button type="reset" className="warning" variant="warning" >Reset</Button>
                                <Button variant="primary" type="submit">Next</Button>
                            </div>
                  
                        </Form>
                        </div>
                        <div className="vector" sm={12} md={4}>
                            <img src={vector} alt="vector"/>
                        </div>
                </section>
               </Container>
            </Row>
        </Container>
    </>
    );
    }
}

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

const mapDispatchToProps = (dispatch) => {
    return {
        createStudent: (student) => {
            dispatch(createStudent(student));
        },
    };
};
export default connect(mapStateToProps,mapDispatchToProps)(StudentDetails);

And inside the ThankYou page i am trying to get the username which was supposed to be entered by user. And because i am not using login system inside my feedback app, so how can i apply auth guards to my application?

import React from 'react';
import { Link } from "react-router-dom";
import Navbar from '../layout/Navbar';

const ThankYou = (props) => {
    return (
        <>
            <Navbar/>
            <div className="center thankyou-div">
                <h1 className="heading">ThankYou</h1>
                <h3><strong><span className="text-warning">{props.userName}</span> for your valuable feedback</strong></h3>
                <p className="feedback-link"><Link to="/">Go to Feedback again</Link></p>
            </div>
        </>
    );
}

export default ThankYou;
Wasim
  • 31
  • 1
  • 4

1 Answers1

1

You can try pushing the user name:

this.props.history.push({
  pathname: '/feedback',
  state: { userName: this.state.name }
})

And in the Thank You component, obtain it like this:

const ThankYou = (props) => {
    return (
        <>
            <Navbar/>
            <div className="center thankyou-div">
                <h1 className="heading">ThankYou</h1>
                <h3><strong><span className="text-warning"> {props.location.state.userName}</span> for your valuable feedback</strong></h3>
                <p className="feedback-link"><Link to="/">Go to Feedback again</Link></p>
            </div>
        </>
    );
}

With React-Router history.push, you can also send additional data. Here you will find more examples: How to pass params with history.push/Link/Redirect in react-router v4?

UPDATE: The solution can be found here The issue was that the Student data wasn't saved in the studentReducer. Therefore, the correct user details can now be pulled from the final Thank You Component using Redux.

gonpeche
  • 99
  • 5
  • TypeError: props.location.state is undefined (Getting this error in ThankYou Component) – Wasim Mar 30 '21 at 14:42
  • Try console.log *props*. Let's see if you are receiving something. – gonpeche Mar 30 '21 at 14:44
  • inside location state is undefined – Wasim Mar 30 '21 at 14:53
  • Receiving pathname and other stuffs but the state is undefined. – Wasim Mar 30 '21 at 15:05
  • Ok, you could then validate that the state holds the user name correctly. Try console.log the user name before hitting the Next button and then match it with the props the Thank You component receives. The fix should be there. – gonpeche Mar 30 '21 at 15:22
  • Inside student details component userName is undefined. state is not holding the username in it. this.props.history.push({ pathname: '/feedback', state: { userName: this.state.name } }) console.log("Username",this.state.userName); – Wasim Mar 30 '21 at 18:44
  • Inside StudentDetails Component the name of the user is saved under the variable called "name". When you push that variable to the Router, you are changing the variable "name" to "userName" when you do "this.props.history.push({ pathname: '/feedback', state: { **userName**: this.state.name } })". Try doing this: this.props.history.push({ pathname: '/feedback', state: { name: this.state.name } }) And from the Thank You, do this: {props.location.state.name} – gonpeche Mar 30 '21 at 18:57
  • It stills undefined – Wasim Mar 30 '21 at 19:36
  • 1. Student Details 2. Feedback Form 3. More Details 4. ThankYou i'm travelling through the components in this manner.Is it the reason i'm not able to access the props from student details directly in the Thankyou component?? – Wasim Mar 30 '21 at 19:47
  • Well, I would need to see the full code to understand why it isn't working. Another thing you can do is to pull the user details from the store, since you are dispatching the user data when "Next" is clicked. Just follow this tutorial and connect the Thank You component to Redux and grab the user data via the component's props --> https://dev.to/terrythreatt/what-is-mapstatetoprops-in-redux-427 – gonpeche Mar 30 '21 at 20:17
  • https://codesandbox.io/s/interesting-borg-exwo7?file=/src/App.js here is the codesandbox link of the project – Wasim Mar 30 '21 at 20:19
  • Here you go, problem solved: https://codesandbox.io/s/elegant-gauss-npym5?file=/src/store/reducers/studentReducer.js The issue was that you weren't saving the student data in Redux. Check the Thank You component and how the data is being pulled. Also, check the studentReducer file. Also, bear in mind that I commented the MaterialTable module from the Dashboard component file, otherwise the app won't run in CodeSandBox (just in case you intend to use the final code provided in the snippet) – gonpeche Mar 30 '21 at 21:57
  • Thanks mate, Can you suggest how can i apply auth guards so no one can directly access the feedback form or other pages. This should be done step wise. – Wasim Mar 31 '21 at 08:51