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>
<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>
<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.