Assign numbers to alphabets in react js - javascript

Firstly, i wanna assign numbers to all alphabets like this:a=1,b=2,c=3,d=4 etc.
Secondly, I want to create an input field and submit Button.
Thirdly, when I enter alphabets on that input field,
(eg: abcd it shows 1234 because i already mentioned above, a=1, b=2, c=3, d=4).
And last, I wanna to add them (eg: I entered "abcd" and output is 1234 and add them.)Final Output for abcd is 1+2+3+4 =10.
import React,{useState} from 'react'
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"
const Data = () => {
const [data, setData] = useState({a: 1,b: 2,c: 3,d: 4,e: 5,f: 6,g: 7,h: 8,i: 9,j: 10,k: 11,l: 12,m: 13,n: 14,o: 15,p: 16,q: 17,r: 18,s: 19,t: 20,u: 21,v: 22,w: 23,x: 24,y: 25,z: 26})
const changeHandler = e => {
setData({...data,[e.target.name]:[e.target.value]})
}
const submitHandler=e=> {
e.preventDefault();
}
return (
<div>
<form onSubmit={submitHandler}>
<input type="text"onChange={changeHandler}/><br/>
<button className="btn btn-primary"onClick={()=>setData(console.log(data))}>Click</button><br/>
</form>
</div>
)
}
export default Data

Presented below is one possible way to achieve the desired objective.
Code Snippet
const {useState} = React;
const Thingy = ({...props}) => {
// state variable to hold user input
const [userInput, setUserInput] = useState('');
// state variable to track user submit button click
const [showResult, setShowResult] = useState(false);
// method to update "userInput" state variable
const handleChange = ev => (setUserInput(ev.target.value), setShowResult(false));
// method to conver a single character (a to z) into number (1 to 26)
const convertChar = ch => {
const c = ch.toLowerCase();
// if user input is a digit, ensure return value is a "string"
if ('0' <= c && c <= '9') return ch.toString();
if (!('a' <= c && c <= 'z')) return ch; // do not convert non-alpha
return c.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
};
// method to transform user-input into numbers
const transformInput = () => userInput
.split('') // split the string into array of individual letters
.map(c => convertChar(c)) // use the "convertChar" method
.join(' '); // join back to string with "space" seperator
// added a "space" only for rendering to UI
// method to find the sum/total of numbers
const getResult = () => userInput
.split('') // convert string to array of individual letters
.map(c => convertChar(c)) // transform a-z to numbers 1-26
.filter( // discard any characters except a-z, A-Z
c => (
typeof c !== 'string' && // check letter is no longer "string"
!isNaN(c) // and it is not "NaN"
)
)
.reduce( // add the numbers using ".reduce()"
(total, itm) => total + itm, 0
);
// return the JSX that will be rendered on the UI
// ----
// description of elements
// ^^^^^^^^^^^ ^^ ^^^^^^^^
// 1. label - "enter text" to prefix the input-box
// 2. input - to obtain the user input
// 3. "<p>" - paragraph elt to show a-z transformed to 1-26
// 4. button - submit button to calculate the sum
// 5. "<p>" - paragraphe elt to show the result of the summation
// -----
// NOTE: Items 4, 6 and conditionally rendered
return (
<div>
<div>
<label htmlFor={'usrinp'}>Enter text: </label>
<input
id="usrinp"
value={userInput}
onChange={handleChange}
/>
</div>
{
userInput.length > 0 &&
<p>Converted text to: {transformInput()}</p>
}
<button onClick={() => setShowResult(true)}>
Submit
</button>
{
showResult && <p>Result is: {getResult()}</p>
}
</div>
);
};
ReactDOM.render(
<div>
<h4>Transform User input text to numbers</h4>
<Thingy />
</div>,
document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />
Explanation
Inline comments added to the snippet above.

you can do something like this
const dictionary = Object.fromEntries(Array(26).fill('a').map((s, i) => [String.fromCharCode(s.charCodeAt() + i), i + 1]))
export default function App() {
const [string, setString] = useState('')
const [numbers, setNumbers] = useState([])
const [total, setTotal] = useState(0)
const changeHandler = (e) => {
setString(e.target.value)
}
useEffect(() => {
setNumbers(
string.toLowerCase().split('').map(c => dictionary[c])
)
}, [string])
const calculateTotal = () => {
setTotal(numbers.reduce((a, b) => a + b, 0))
}
return (
<div className="App">
<div>{numbers.join(' ')}</div>
<input type="text" onChange={changeHandler} value={string}/><br/>
<button className="btn btn-primary"onClick={calculateTotal}>Click</button><br/>
{total > 0 && <div>the total is {total} }
</div>
);
}

Related

how can i output the result of one input tag in another input tag

let say a= 20 and b = 10 and c= 12 ..........etc
output of <input/> two = input value in <input /> one field * (a or b or c.....)
also
output of <input/> one = input value in <input/> two field / (a or b or c.....)
let say a= 20 and b = 10 and c= 12 ..........etc
output of <input/> two = input value in <input /> one field * (a or b or c.....)
also
output of <input/> one = input value in <input/> two field / (a or b or c.....)
let say a= 20 and b = 10 and c= 12 ..........etc
output of <input/> two = input value in <input /> one field * (a or b or c.....)
also
output of <input/> one = input value in <input/> two field / (a or b or c.....)
let say a= 20 and b = 10 and c= 12 ..........etc
output of <input/> two = input value in <input /> one field * (a or b or c.....)
also
output of <input/> one = input value in <input/> two field / (a or b or c.....)
let say a= 20 and b = 10 and c= 12 ..........etc
output of <input/> two = input value in <input /> one field * (a or b or c.....)
also
output of <input/> one = input value in <input/> two field / (a or b or c.....)
import { useEffect } from "react";
import { useState } from "react";
export default function Converter() {
const [fromUnit, setFromUnit] = useState(1);
const [toUnit, setToUnit] = useState(1);
const [inputValue1, setInputValue1] = useState(1);
const [inputValue2, setInputValue2] = useState(1);
const [value, setValue] = useState();
const [result, setResult] = useState();
const lenghts = [
{ id: 1, value: "meter" },
{ id: 2, value: "kilometer" },
{ id: 3, value: "centimetre" },
{ id: 4, value: "milimetre" },
];
function setUnit1(e) {
const value = e.target.value;
if (value === 1) {
setFromUnit(1);
} else if (value === 2) {
setFromUnit(1000);
} else if (value === 3) {
setFromUnit(100);
} else if (value === 4) {
setFromUnit(0.01);
}
}
function setUnit2(e) {
const value = e.target.value;
if (value === 1) {
setToUnit(1);
} else if (value === 2) {
setToUnit(1000);
} else if (value === 3) {
setToUnit(100);
} else if (value === 4) {
setToUnit(0.01);
}
}
useEffect(() => {
setResult((toUnit * parseFloat(inputValue1)) / fromUnit);
setValue((toUnit * parseFloat(inputValue2)) / fromUnit);
}, [toUnit, fromUnit, inputValue1, inputValue2]);
console.log(value);
console.log(result);
return (
<div>
<div>
<input
type="text"
value={value}
onChange={(e) => setInputValue1(e.target.value)}
/>
<select onChange={setUnit1}>
{lenghts.map((lenght) => (
<option key={lenght.id} value={lenght.id}>
{lenght.value}
</option>
))}
</select>
</div>
<div>
<input
type="text"
value={result}
onChange={(e) => setInputValue2(e.target.value)}
/>
<select onChange={setUnit2}>
{lenghts.map((lenght) => (
<option key={lenght.id} value={lenght.id}>
{lenght.value}
</option>
))}
</select>
</div>
</div>
);
}

how to validate after checkboxed clicked?

I broke my Code down to make it look simple
const [factor, setfactor] = useState(1);
const [nullify, setNullify] = useState(1);
const Price = 10;
const Bonus = 15;
const finalPrice = (Price * factor - Bonus) * nullify;
// start 5 = (10 * 2 -15)* 1
// after Click -5 = (10 * 1 -15)* 1
//what i want 0 = (10 * 1 -15)* 0
const handleFactor = () => {
setfactor(1)
validate()
};
const validate = () => {
if (finalPrice <= 0) {
setNullify(0);
}
};
useEffect(() => {
handleFactor();
}, [factor]);
//HTML Stuff
return (
<>
<input type="checkbox" onClick={handleFactor} />
<input type="checkbox" onClick="activate bonus" />
{finalPrice}
</>
);
I want, if the bonus make it below 0 the final price should not be a minus number , instead it should becomes a zero itself - but it doesn't work.
I know, that the final price will be 5 when the validation do it's thing. But how do I get the newPrice?
State updates are asynchronous, so you can get the updated state on the next render. When you do this
const handleFactor = () => {
setfactor(1)
validate()
};
the state haven't updated yet, and validate would use the previous (valid) values. You'll need to move validate to the next render for this to work.
However, you don't need another state to ensure that finalPrice is above 0. Use Math.max(price * factor - bonus, 0)to get the max between the final price and0` (or any other minimum number):
const { useState, Fragment } = React;
const Demo = ({ price, bonus }) => {
const [factor, setfactor] = useState(2);
const finalPrice = Math.max(price * factor - bonus, 0);
const handleFactor = () => {
setfactor(1)
};
return (
<Fragment>
<input type="checkbox" onClick={handleFactor} />
{finalPrice}
</Fragment>
);
};
ReactDOM
.createRoot(root)
.render(<Demo price={10} bonus={15} />);
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="root"></div>

How can I programmatically update the helperText of a Material UI TextField based on the value of the TextField?

I am trying to update a Material UI TextField's helperText based on the value of the TextField. Here's what I have:
const defaultScores = {
STR: 10,
DEX: 10,
CON: 10,
INT: 10,
WIS: 10,
CHA: 10
}
const [abilityScores, setAbilityScores] = React.useState(defaultScores);
const handleScoreChange = (event) => {
const { ability, score } = event.target;
setAbilityScores({
...abilityScores,
[ability]: score,
});
const modifier = (abilityScores.STR - 10) / 2;
document.getElementById("str-input").setAttribute("helperText", modifier >= 0 ? "+" + modifier : "-" + modifier);
};
<TextField id="str-input" name="str" label="STR" defaultValue={abilityScores.STR} fullWidth margin="dense" type="number" variant="standard" onChange={handleScoreChange} />
When I update the value of the TextField, nothing happens with the helperText. Granted this is my first time using Material UI so I'm unfamiliar. Also I don't normally touch JS so I'm out of my element here in the first place. If more info is necessary then please let me know.
The whole point of using front-end frameworks like React, at least in the context of DOM changes, is to avoid things like document.getElementById....
What you need is one more state variable.
const [helperText, setHelperText] = useState("");
And then in your handleScoreChange
const handleScoreChange = (event) => {
const { ability, score } = event.target;
setAbilityScores({
...abilityScores,
[ability]: score,
});
const modifier = (abilityScores.STR - 10) / 2;
setHelperText(modifier >= 0 ? "+" + modifier : "-" + modifier)
};
Finally in your TextField
<TextField helperText={helperText} {... other attributes} />
I don't think using document.getElementById is suitable for React, it's more of something for vanilla JS.
Also not so sure of your handleScoreChange function, but it's likely not going to work since event.target only has .value that outputs the text value when new characters are typed. So usually the implementation for text change is going to be:
const handleScoreChange = (event) => setAbilityScores(event.target.value);
In react, you can handle this with useMemo hooks, where you'll define helperText with useMemo and make modifier as the dependencies such that the value will change when the value of modifier change.
import { useState, useMemo } from "react";
const FunctionalComponent = () => {
const defaultScores = {
STR: 10,
DEX: 10,
CON: 10,
INT: 10,
WIS: 10,
CHA: 10
}
const [abilityScores, setAbilityScores] = useState(defaultScores);
const modifier = useMemo(() => (abilityScores.STR - 10) / 2, [abilityScores]);
const helperText = useMemo(
() => modifier >= 0 ? "+" + modifier : "-" + modifier,
[modifier]);
const handleScoreChange = (event) => setAbilityScores(event.target.value);
return (
<TextField
helperText={helperText}
// other props
/>
);
};

Scramble per letter using javascript

How can I scramble the words per letter?
My code scramble the whole words...
I can't seem to change it per letter. Since I'm new to Vue.js
I'm using Vue.js in here.
const sampleText1 = 'インバウント'
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const charactersLength = characters.length
export default {
data() {
return {
sam01: sampleText1,
}
},
setup() {
const texts = reactive({
text1: sampleText1,
})
const scrambleText = (text, name) => ({ progress }) => {
if (progress === 100) {
texts[name] = text
} else if (Math.floor(progress) % 20 === 0) {
texts[name] = text.replace(
/./g,
characters.charAt(Math.floor(Math.random() * charactersLength))
)
}
}
}
current output
expected output
You can pass the replacement as a function instead of single string which will invoke for each match.
...
texts[name] = text.replace(
/./g,
() => characters.charAt(Math.floor(Math.random() * charactersLength))
)
...

Logical NaN Error in my React Typescript counter for win percentage

I am making a simple Typescript counter to track my win percentage in my Legends of Runeterra games I play. I can't figure out why when I increment a win or a loss I get NaN as my win percentage. The logic seems fine (obviously you can't decrement right now, that's a problem for later), I just want to focus on fixing the NaN error for now.
Here's my counter component:
import React, { useState } from 'react'
// add a ? after the type name if you want any one of these to be optional, ex: wins?
const Counter: React.FC<{
initialGamesPlayed: number
initialWins: number
initialLosses: number
initialWinPercentage: number
initialDeckName: string
}> = ({
initialDeckName,
initialWinPercentage,
initialWins,
initialLosses,
initialGamesPlayed,
}) => {
const [deckName, setDeckName] = useState(initialDeckName)
const [wins, setWins] = useState(initialWins)
const [losses, setLosses] = useState(initialLosses)
const [totalGames, setTotalGames] = useState(initialGamesPlayed)
const [winPercentage, setWinPercentage] = useState(initialWinPercentage)
const incrementWins = () => {
setWins(wins + 1)
winPercentageCalc()
console.log(winPercentage)
}
const decrementWins = () => {
if (wins > 0) setWins(wins - 1)
winPercentageCalc()
}
const incrementLosses = () => {
setLosses(losses + 1)
winPercentageCalc()
console.log(winPercentage)
}
const decrementLosses = () => {
if (losses > 0) setLosses(losses - 1)
winPercentageCalc()
}
const winPercentageCalc = () => {
setTotalGames(wins + losses)
setWinPercentage((wins / totalGames) * 100)
}
return (
<div>
<p>Deck Name: </p>
<p>wins: {wins} </p>
<button onClick={incrementWins}>+</button>
<button onClick={decrementWins}>-</button>
<p>losses: {losses}</p>
<button onClick={incrementLosses}>+</button>
<button onClick={decrementLosses}>-</button>
<p>Win Percentage: {winPercentage} % </p>
</div>
)
}
export default Counter
Thanks for taking a look!
The setWins, setLosses, setTotalGames and setWinPercentage are all asynchronous functions. So the first time your call winPercentageCalc, this is what happens:
const winPercentageCalc = () => {
setTotalGames(wins + losses) // This is asynchronous, so...
setWinPercentage((wins / totalGames) * 100) // totalGames = 0 => NaN
}
When you divide wins by totalGames, totalGames has not been updated so you divide by 0 which gives NaN (Not a Number) as a result

Categories

Resources