Home > database >  Using React.js, how to take information from a form and use conditional rendering
Using React.js, how to take information from a form and use conditional rendering

Time:01-19

I am currently working on a React project that uses a form. In my form are questions and in those questions a user can select the answer that sounds more like them, the user can finish the survey and hit submit. Currently in my application, when a user hits submit the answers will show in the console. My goal, is to take those printed answers from the console and use a if..else statement (conditional rendering) to take the user to a specific page. I am having issues understanding the concept of how I can perform this action.

Test case

  • To take information from the form and use an if/else statement to take the use to another page

Step 1) The user answers the questions and hits submit. Expectation: The selection of answers gets submitted Actual: The selection of answers gets submitted, but they are submitted to the console.

Step 2) The users selected answers are rendered in an if..else statement (or another method), and the user is sent to a specific page according to their answers. Ex. User selects

{ "gender": "male", "userAge": "young", "goals": "active" } and is then sent to a specific page for that user. Expectation: After the answer object is submitted the information is taken and used to send the user to another page. Actual: A LOT OF FAILURE!!

for a while I was getting the error. Uncaught TypeError: props.getData is not a function.

I am having a hard time completing this current task and questioning if I am going about the situation the correct way, also if using an if/else statement or ternary operator (which is also a question i have but can be delt with later) is the right option.

If I could get some help with my issue I would appreciate it. Thank you!

import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />)
import React, {useState} from 'react';
import Introduction from './components/introduction';
import Questions from './components/beginning';
import Male from './components/questions';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';

 export default function App() {



  return (
    //Revisit <Route path="/questions" element= {<Male />} /> for Readability!!
    <Router>
      <Routes>
        <Route path= "/" element={<Introduction />} />
        <Route path="/beginning" element= {<Questions  />} />
        <Route path="/personalExercise" element={<personalExercise/>} />
        <Route path="/questions" element= {<Male />}  /> 
      </Routes>
    </Router>
  );
}
       
import React, {useState} from 'react';
import Form from 'react-bootstrap/Form';


export default function Questions(props) {
    
    const[formData, setFormData] = useState({
        gender: "", 
        userAge: "", 
        goals:"", 
    });

    function handleChange(event) {
        const { name, value, type, checked } = event.target;
       setFormData(prevFormData => {
        return {
            ...prevFormData,
            [name]: type === 'checkbox' ? checked : value 
        };
       });
    }

    function handleSubmit(event) {
        event.preventDefault()
         console.log(formData)
       };
 
    return (
        <>
        <header>Questions</header>

        <Form onSubmit={handleSubmit}>
            <fieldset>
            <legend>What was your gender at birth</legend>
                <input 
                type='radio'
                id = 'male'
                name = 'gender' 
                value = 'male'
                checked={formData.gender === "male"}
                onChange={handleChange}
                />
                <label htmlFor="male"> Male </label>
                <br />

                <input 
                type='radio'
                id='female'
                name='gender'
                value = 'female' 
                checked={formData.gender === "female"}
                onChange={handleChange}
                />
                <label htmlFor="female"> Female </label>
                <br />
            </fieldset>

                    <fieldset>
                        <legend>How old are you?</legend>

                        <input 
                        type='radio'
                        id="young"
                        name="userAge"
                        value="young"
                        checked={formData.userAge === "young"}
                        onChange={handleChange}
                        />
                        <label htmlFor="young"> 18-28 </label>
                        <br />

                        <input 
                        type='radio'
                        id="middleAged"
                        name="userAge"
                        value="middleAged"
                        checked={formData.userAge === "middleAged"}
                        onChange={handleChange}
                        />
                        <label htmlFor="middleAged"> 29-39 </label>
                        <br />

                        <input 
                        type='radio'
                        id="older"
                        name="userAge"
                        value="older"
                        checked={formData.userAge === "older"}
                        onChange={handleChange}
                        />
                        <label htmlFor="older"> 40-50 </label>
                        <br />

                        <input 
                        type='radio'
                        id="senior"
                        name="userAge"
                        value="senior"
                        checked={formData.userAge === "senior"}
                        onChange={handleChange}
                        />
                        <label htmlFor="senior"> 51  </label>
                        <br />
                    </fieldset>
                    <br />

                    <fieldset>
                        <legend>What kind of fitness would you prefer?</legend>

                        <input 
                        type="radio"
                        id="active"
                        name="goals"
                        value="active"
                        checked = {formData.goals === "active"}
                        onChange={handleChange}
                        />
                        <label htmlFor='active'>To stay active!</label>
                        <br />

                        <input
                        type="radio"
                        id="weight"
                        name="goals"
                        value= "weight"
                        checked = {formData.goals === "weight"}
                        onChange={handleChange}
                        />
                        <label htmlFor="weight"> To loose weight</label>
                    </fieldset>
                    <br />

                    <button>Submit</button>
                    </Form>


                </>
    )
}

CodePudding user response:

Use useNavigate hook

const navigate = useNavigate()
function handleSubmit(event) {
  event.preventDefault()
  navigate('/path/here');
};

CodePudding user response:

Like another use said, use useNavigate() to navigate to another route. As for your conditional, you just need to check the formData state after the user submits. I would do something like this:

function handleSubmit(event) {
  event.preventDefault()
  navigate(getPath());
};

const getPath = () => {
    switch (formData) {
        case { gender: "male", userAge: "young", goals: "active" }: return "pathA";
        break;
        case { gender: "female", userAge: "young", goals: "active" }: return "pathB"
        break;
        etc...
     }
}

Now, I'm not sure if a switch is the best option for what you are doing, but maybe that will help.

As for having access to the users form data in another component, you either need to make the formData state in the parent component then drill it down to all the components you need, or you need to create a context so that you can access that data from any component. Look up React Context.

  • Related