0

I have written a react component which outputs a HTML form with two input's and a button.

Once the button is clicked when can see sum of numbers which we entered in input.

the code is as follows,

import React, { Fragment, useState, useEffect, useReducer } from 'react'; 

const AdderExampleOne = () => {

    const [numOne, setNumOne] = useState("");
    const [numTwo, setNumTwo] = useState("");
    const [add, setAdd] = useState(0);
    
    const [counterStyle, setCounterStyle] = useState({
        "fontSize" : "350px",
        "fontWeight" : "bold",
        "color" : "#483d8b"
    });

    const sumReducer = (state, action) => {
        switch(action.type){
            case "DEFAULT_NUM" :
                return {
                    ...state,
                    "sum" : ""
                }
            case "ADD_NUM" :
                return {
                    ...state,
                    "sum" : action.sum
                }
            default:
                throw new Error();    
        }
    }
    
    const [state, dispatch] = useReducer(sumReducer, {        
        "sum" : ""
    });

    useEffect(()=>{
        dispatch({ 
            "type" : "DEFAULT_NUM" 
        });

        if(add !== undefined && add !== ""){
            dispatch({
                "type" : "ADD_NUM",
                "sum" : add
            });
        }
        
    }, [add])


    return (
        <Fragment>
            <form className="form-inline">
                <div className="form-group">
                    <label  for="numOneId" 
                            className="sr-only">Num One</label>
                    <input  type="text" 
                            className="form-control" 
                            id="numOneId" 
                            placeholder="Num One" 
                            value={numOne}
                            onChange={event => setNumOne(event.target.value)} />
                </div>
                &nbsp;
                <div className="form-group">
                    <label  for="numTwoId" 
                            className="sr-only">Num Two</label>
                    <input  type="text" 
                            className="form-control" 
                            id="numTwoId" 
                            placeholder="Num Two"
                            value={numTwo} 
                            onChange={event => setNumTwo(event.target.value)} />
                </div>
                &nbsp;
                <button type="button" 
                        className="btn btn-primary"
                        onClick={()=>{
                            let total = parseInt(numOne) + parseInt(numTwo);                            
                            setAdd(total);
                        }}>Add</button>
            </form>
            <div>
                <span style={counterStyle}>{state.sum}</span>
            </div>
        </Fragment>
    )
}

export default AdderExampleOne;

Please suggest how will I further improve using useReducer more effectively.

Output Screen

Rahul Shivsharan
  • 2,481
  • 7
  • 40
  • 59
  • Do you want to add two numbers using useReducer hook or anything else please explain more about the problem? – Gulshan Aggarwal Feb 21 '22 at 13:57
  • Just do addition of two numbers and display the total. that's it. But I need to do this using "useReducer" and "dispatcher" just for learning purpose – Rahul Shivsharan Feb 21 '22 at 14:11
  • The answer you received didn't work? – Gulshan Aggarwal Feb 21 '22 at 14:12
  • It will, but can I can further optimise. Like whether I have to do useState as many times as many numbers or can I club it ? Please suggest. – Rahul Shivsharan Feb 21 '22 at 14:17
  • it totally depends upon the requirements suppose you have to show your addition result to other components then you should take only sum field in your initial state or if you want to show numberone and numbertwo field for other components then you need three fields in your initial state. – Gulshan Aggarwal Feb 21 '22 at 14:21
  • What If I have 10 text input and I need to do sum of those number, so I should to const [num1, setNum1] = useState, [num2, setNum2] = useState, [num3, setNum3] = useState... 10 times ? – Rahul Shivsharan Feb 21 '22 at 15:13
  • You can do but the better solution will be by taking all ten numbers as key pair value inside your initial state. Take a look at the answer from the following URL - https://stackoverflow.com/questions/57305109/using-react-hooks-with-more-than-one-key-value-pair-in-state-object – Gulshan Aggarwal Feb 22 '22 at 03:57

1 Answers1

0

If you only want to store the sum results using useReducer then follow this

 const [numOne, setNumOne] = useState("");
 const [numTwo, setNumTwo] = useState("");
 const sumReducer = (state, action) => {
    switch(action.type){
        case "SUM" :
            return {
                ...state,
                "sum" : action.payload
            }
        default:
            return state;
               
    }
    }
     const [state, dispatch] = useReducer(sumReducer, {        
    "sum" : ""
    });
    const submitForm=()=>{
        dispatch({type:"SUM",payload:numOne+numTwo})
    }
return (
    <Fragment>
        <form className="form-inline" onSubmit={submitForm}>
            <div className="form-group">
                <label  for="numOneId" 
                        className="sr-only">Num One</label>
                <input  type="text" 
                        className="form-control" 
                        id="numOneId" 
                        placeholder="Num One" 
                        value={numOne}
                        onChange={event => setNumOne(event.target.value)} />
            </div>
            &nbsp;
            <div className="form-group">
                <label  for="numTwoId" 
                        className="sr-only">Num Two</label>
                <input  type="text" 
                        className="form-control" 
                        id="numTwoId" 
                        placeholder="Num Two"
                        value={numTwo} 
                        onChange={event => setNumTwo(event.target.value)} />
            </div>
            &nbsp;
            <button type="submit" 
                    className="btn btn-primary"
                    >Add</button>
        </form>
        <div>
            <span style={counterStyle}>{state.sum}</span>
        </div>
    </Fragment>
    
Asad Haroon
  • 476
  • 3
  • 9