Do calculations with users input - javascript

I'm trying to do simple calculations with a new value in an updated state. I'm simply trying to divide a users input, with another number. I am a total beginner, so forgive me for the rooky question! Here's my code which isn't working for me. There are no errors, it's just not showing the resulting figure from the calculation -
import { useState } from "react";
const Counter = () => {
const [area, setArea] = useState("");
const newArea = () => {
setArea(area.target.value);
};
const deckBoards = (newArea) => {
(newArea / 0.145).toFixed(2);
};
return (
<div label="Deck">
<h2>Total area of deck</h2>
Area
<input
placeholder="Enter area here"
type="text"
onChange={newArea}
type="number"
/>
<br />
<h2>Deck boards</h2>Deck boards at 140mm wide : {deckBoards} lineal metres
</div>

You are missing event in the newArea function and DeckBoards needs to be area in JSx
Try this
import { useState } from "react";
const Counter = () => {
const [area, setArea] = useState("");
const deckBoards = (newArea) => {
// it was missing return statement
return (newArea / 0.145).toFixed(2);
};
const newArea = (e) => {
const value = e.target.value;
// Calculate here
const calculated = deckBoards(value);
// Update value
setArea(calculated);
};
return (
<div label="Deck">
<h2>Total area of deck</h2>
Area
<input
placeholder="Enter area here"
type="text"
onChange={newArea}
type="number"
/>
<br />
<h2>Deck boards</h2>Deck boards at 140mm wide : {area} lineal metres
</div>
);
}

Related

JavaScript cant get value of input from my items

making beginer site and im getting api of crypto Coins and i put them on home page . i put "buy" button with input that i want to fill and buy . i have trying to use getElementsByClassName/ id and its only return the first item. if i log the first item its return value . but if i log all the rest of the items its return "undefined". so i have search a hours on solution and i have found that im using the same "classname" to all items - because of that it return only the first item value . but the problem that i have no idea and i can't find solution.
adding my code . (the map is on homepage)
site image with log
coin.js
import React, { useContext, useState } from 'react'
import './Coin.css';
import { Context } from '../src/context/Context'
const Coin = ({
name,
price,
symbol,
marketcap,
volume,
image,
priceChange
}) => {
const { user, dispatch } = useContext(Context);
// buyCoin function ( buy coin -> checking if user can buy)
function buyCoin() {
const coinNumber = document.getElementsByClassName("buyInput").value;
const coinPrice = { price }.price;
const wallet = user.wallet;
if (coinNumber * coinPrice > wallet) {
alert("you dont have enough money");
console.log(coinNumber);
return false;
} else {
console.log(coinNumber);
alert("purchase completed");
return true;
};
}
return (
<div className='coin-container'>
<div className='coin-row'>
<div className='coin'>
<img src={image} alt='crypto' />
<h1>{name}</h1>
<p className='coin-symbol'>{symbol}</p>
</div>
<div className='coin-data'>
<p className='coin-price'>${price}</p>
<p className='coin-volume'>${volume.toLocaleString()}</p>
{priceChange < 0 ? (
<p className='coin-percent red'>{priceChange.toFixed(2)}%</p>
) : (
<p className='coin-percent green'>{priceChange.toFixed(2)}%</p>
)}
<p className='coin-marketcap'>
${marketcap.toLocaleString()}
</p>
//button to buy the coin
<button className='buybtn' onClick={buyCoin}>Buy</button>
<input type="number" className="buyInput"></input>
</div>
</div>
</div>
);
};
export default Coin;
If you want the value from the input field, I recommend using the state to keep track of the value.
Something like:
const { coinNumber, setCoinNumber } = useState();
And add
<input
type="number"
className="buyInput"
value={coinNumber}
onChange={setCoinNumber }
></input>
Then you can get your value from coinNumber to use in the buyCoin function.

How to preserve spacing when storing a string into an array? JavaScript React.js

I have a form with a <textarea>. On submit that string gets stored into an array. Sometimes the strings have blank lines or additional spacing and I want to preserve this spacing. Right now, the only spacing preserved is the spacing between words. The handleSubmit component consist of a useRef hook that is pushed into the array. I'm looking for another approach for storing the string that would preserve spacing. I appreciate all ideas! Thank you for your time!
const textAreaRef = useRef();
const [entryArray, setEntry] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
const updatedList = [...entryArray];
updatedList.push(textAreaRef.current.value);
textAreaRef.current.value = ""; // Clears value
setEntry(updatedList);
}
return (
<div>
<form class="entryForm" onSubmit={handleSubmit} >
<label for="newEntryId">
<span>New Entry:</span>
<textarea type="text" id="newEntryId" name="newEntryName" rows="30" cols="75"
defaultValue="What's on your mind?" ref = {textAreaRef}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
)
Can't replicate the issue, works fine.
Vanilla js example, but works the same in React
const area = document.querySelector('textarea')
const button = document.querySelector('button')
const saved = []
button.addEventListener('click', () => {
saved.push(area.value)
area.value = ''
console.log(saved)
})
<textarea></textarea>
<button>save</button>

how to create an array of arrays in react?

I'm trying to code a wordle clone using React, but the twist is that the player can choose the number of attempts and the length of the word. And i want to rendre the box depending on these two parameter so i used the following line :
var grid = Array(this.props.nbrAttempts).fill(0).map(row => new Array(this.props.wordLenght).fill(' '))
the first time the component render i get a 4*4 array, but after changing the parameter i get always a 1*1, and i can't figure what's the problem.
the Box component:
function App() {
const [boxParam, setBoxParam] = useState({nbrAttempts: 4, wordLenght : 4,});
let renderBox = ()=>{
setBoxParam({
nbrAttempts: document.getElementById('nbAttempts').value,
wordLenght : document.getElementById('wordLength').value,
})
}
return (
<div className="App">
{/* add input field with number of attempts as label */}
<label htmlFor="nbAttempts">Attempts</label>
<input type="number" id="nbAttempts"/>
<label htmlFor="nbAttempts">Word length</label>
<input type="number" id="wordLength"/>
<button onClick={()=>renderBox()}>OK</button>
<Box nbrAttempts={boxParam.nbrAttempts} wordLenght={boxParam.wordLenght} />
</div>
);
}
I just replaced
var grid = Array(this.props.nbrAttempts).fill(0).map(row => new Array(this.props.wordLenght).fill(' '))
with
let grid = [];
for (let i = 0; i < this.props.nbrAttempts; i++) {
grid.push(new Array(this.props.wordLenght).fill('_'));
}
and everything just worked fine

React : Display an error message when clicking on the "submit" button if the user enters text

I create a project in React. I would like that when the user clicks on the "submit" button it shows him an error message if in the input "FormDebut" he enters "text" type characters.
But I can't do this :'( , could you help me please? Thanks in advance !
FormulaireReservations.js :
export default function FormulaireReservation() {
return (
<div className="Formulaire">
<Logo/>
<h2><center>Formulaire de réservation</center></h2>
<FormDebut/>
<center><input type="submit" value="Submit" /></center>
</div>
);
}
Component FormDebut.js :
const [value, setValue] = React.useState("");
const onChange = (e) => {
const formattedValue = formatInput(e.target.value);
if (formattedValue.length < 6) {
setValue(formattedValue);
}
}
const formatInput = (input) => {
if (input.length > 2 && input[2] !== ":") {
return input.substring(0, 2) + ":" + input.slice(2);
}
return input;
}
return (
<div className="Form">
<div>Début : </div>
<input placeholder="00:00" type="text" onChange={onChange} value={value}/>
</div>
)
}
export default FormDebut; ```
Test this out in a new document, and then from there you can implement it into your work. You can have a parameter were user has to input a number between 1-10 if they do not then you can display an error message. If number is between 1-10 then you can redirect them. isNAN (is not a number) is a condition and is used for validating the input of the user. The function will check if the input is not a number, it will check if the input is less than 1 or more than 10, if all these conditions are true then it will display an error.
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
I'm not sure if I understood your requirements, but seems that when you click submit button you want to check if the input is numeric value. If that's the case, this should work:
https://codesandbox.io/s/infallible-browser-74r5d7?file=/src/App.js
I moved the value state into the Form itself and passing it as a prop to its child. I also added a new state variable called error that is passed to the FormDebut. On click of the submit button, I strip the : from the value and check if I can parse it to a number. If not, I set the error, otherwise I clear out the error.
Hope that helps
Here is something you can modify your components:
in your FormulaireReservations.js:
export default function FormulaireReservation() {
const [value, setValue] = React.useState("");
const [errorMsg, setErrorMsg] = React.useState("");
const handleSubmission = () => {
if (isNaN(value)) {
setErrorMsg('Input should not be a text')
}
}
React.useEffect(() => {
setErrorMsg('')
}, [value])
return (
<div className="Formulaire">
<Logo />
<h2><center>Formulaire de réservation</center></h2>
<FormDebut value={value} setValue={setValue} msg={errorMsg} />
<center><input type="button" onClick={handleSubmission} value="Submit" /></center>
</div>
);
}
and in your FormDebut.js :
function FormDebut({ value, setValue, msg }) {
const onChange = (e) => {
const formattedValue = formatInput(e.target.value);
if (formattedValue.length < 6) {
setValue(formattedValue);
}
}
const formatInput = (input) => {
if (input.length > 2 && input[2] !== ":") {
return input.substring(0, 2) + ":" + input.slice(2);
}
return input;
}
return (
<div className="Form">
<div>Début : </div>
<input placeholder="00:00" type="text" onChange={onChange} value= {value} />
{ msg && <p>{msg}</p> }
</div>
)}export default FormDebut;
So, basically, the value and errorMsg state is passed to another component that contains the input field. Each time changes on the input field will also update the state declared in the parent component. When a user clicks on submit button, it calls a function that is checking if the value is a number or not. Based on that the errorMsg state is updated. And in the FormDebut component, error msg will be shown just after the input field if any msg was set.

React.JS - changing input based on another input

I am trying to change value of input field based on another one and vice versa.
That's create issue, any changed value not displayed in input. Anything I type is not show by input field.
Following which I tried, You can see I am trying to change value of input 1 based on 2 and 2nd input value based on first:
import React, { useState, useEffect } from 'react';
const App = () => {
useEffect(() => {
//fetch api call here
});
const [firstVal, setFirstVal] = useState(0);
const [secondVal, setSecondVal] = useState(0);
const changeFirstValue = (e) => {
setSecondVal(e.target.value / 2);
}
const changeSecondValue = (e) => {
setFirstVal(e.target.value * 2);
}
return (
<div>
<input type='number' value={firstVal} onChange={changeFirstValue}></input>
<input type='number' value={secondVal} onChange={changeSecondValue}></input>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Any help would be greatly appreciated.
If you want to show the division and multiplication relationship between these two elements. Try below code:
const changeFirstValue = (e) => {
setSecondVal(e.target.value);
setFirstVal(e.target.value * 2);
}
const changeSecondValue = (e) => {
setFirstVal(e.target.value);
setSecondVal(e.target.value / 2);
}
return (
<div>
<input type='number' value={firstVal} onChange={changeSecondValue}></input>
<input type='number' value={secondVal} onChange={changeFirstValue}></input>
</div>
);
From what I understood, I think you have to reverse the call of the two functions,
so your code will look like this:
...
<input type='number' value={firstVal} onChange={changeSecondValue}></input>
<input type='number' value={secondVal} onChange={changeFirstValue}></input>
...

Categories

Resources