Currently making a small app that translates text to binary or ASCII. I’ve run into an issue where my code only works if you follow these steps
- type something in the text area
- choose your language
- press the button
I want to make it so I can do it this way as well
- choose your language
- type something in the text area
- press the button
It must have something to do with the message state being undefined if you select a language first.
import { useState, useEffect } from "react"; function Translator() { const [message, setMessage] = useState(""); const [selectedLanguageResult, setSelectedLanguageResult] = useState(""); const [results, setResults] = useState(""); function handleLanguageSwitch(e) { let selectedValue = e.target.value; if (selectedValue === "Ascii") { setSelectedLanguageResult(translateToAscii()); } else if (selectedValue === "Binary") { setSelectedLanguageResult(translateToBinary()); } } function handleChange(e) { setMessage(e.target.value); } function translateToAscii() { let arr = []; for (let i = 0; i < message.length; i++) { arr.push(message.charCodeAt(i)); } return arr.join(" "); } function translateToBinary() { let strOut = ""; for (let i = 0; i < message.length; i++) { strOut += message[i].charCodeAt(0).toString(2) + " "; } return strOut; } function handleClick(e) { e.preventDefault(); setResults(selectedLanguageResult); } return ( <div className="App"> <form> <select name="language" onChange={handleLanguageSwitch}> <option selected disabled> --Choose language-- </option> <option value="Ascii">Ascii</option> <option value="Binary">Binary</option> </select> <textarea type="text" id="message" onChange={handleChange} value={message} ></textarea> <button onClick={handleClick}>Translate</button> </form> <h2>{results}</h2> </div> ); } export default Translator;
Advertisement
Answer
You should keep the language in state and set the result when the user submits.
Have a look at this example: https://codesandbox.io/s/flamboyant-bas-wqso2n?file=/src/App.js
I changed the button to a submit button and put the onClick function into the forms onSubmit (this is how a form should be done in react).
I removed selectedLanguageResult in favour of language state.
The select element I used the value prop = language and set the value to your first option as an empty string. React prefers this (you may have noticed a warning in the console).
Finally when the user submits the form, that is where the result is calculated and set.
Hope that makes sense.