I am trying to write a simple program that allows you to enter your first and last name in input fields so you get a greeting based on your name. But I cannot get it to work.
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [Savedinput, setSavedinput] = useState({Fname:' ' , Lastname:''} );
const ChangeFirst = (e) => {
setSavedinput Savedinput.Fname(e.target.value);
};
const ChangeLast = (e) => {
setSavedinput Savedinput.Lastname(e.target.value);
console.log(e.target.value);
};
return (
<div className="App">
<input type="Text" onChange={ChangeFirst}></input>
<input type="Text" onChange={ChangeLast}></input>
<h1> hello {Fname} {Lastname} </h1>
</div>
);
}
You can use destructure method.
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [Savedinput, setSavedinput] = useState({Fname:' ' , Lastname:''} );
const onInputChange = (e, attr) =>{
setSavedinput({...Savedinput, [attr]: e.target.value});
}
return (
<div className="App">
<input type="Text" onChange={(e)=>{onInputChange(e, 'Fname)}} value={Savedinput.Fname}></input>
<input type="Text" onChange={(e)=>{onInputChange(e, 'Lastname)}} value={Savedinput.Lastname}></input>
<h1> hello {Savedinput.Fname} {Savedinput.Lastname} </h1>
</div>
);
}
You shouldn't mutate state directly
To change the a state object you can use spread operator. So your code would be something like:
const ChangeFirst = (e) => {
setSavedinput({...SavedInput, Fname: e.target.value})
};
const ChangeLast = (e) => {
setSavedinput({...SavedInput, Lastname: e.target.value})
};
The {...SavedInput} will expand the whole object to the argument and then adding the Fname: ... will overwrite that so the new value will be passed instead.
For more advance usage of form I recommend you to use react-hook-form
You can have 2 states for firstName and lastName
export default function App() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
return (
<div className="App">
<input type="Text" value={firstName} onChange={() => setFirstName(e.target.value)}></input>
<input type="Text" value={lastName} onChange={() => setLastName(e.target.value)}></input>
<h1> hello {firstName} {lastName} </h1>
</div>
);
}
<input type="Text" onChange={ChangeFirst}></input>
<input type="Text" onChange={ChangeLast}></input>
use two states
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
then respectively on your method use the setState for each of them separately
Firstly the setSavedinput is a function and not a variable. It's a function to set the value of the variable used with it. Since you are taking the value from input field the following method might work out for you.
import React, { useState } from "react";
export default function App() {
const [Savedinput, setSavedinput] = useState({Firstname:'' , Lastname:''} );
return (
<div className="App">
<input type="text" value={Savedinput.Firstname} onChange={(e)=>setSavedinput({... Savedinput , Firstname:e.target.value })} />
<input type="text" value={Savedinput.Lastname} onChange={(e)=>setSavedinput({... Savedinput , Lastname:e.target.value })} />
<h1> hello {Firstname} {Lastname} </h1>
</div>
Instead of declaring a function , you can do it inline for this purpose .
Also I would suggest you to keep the variable names in an order. This is gonna you a lot.
You can use this for the object and ...savedinput to maintain the existing object with updating only changed value
export default function App() {
const [savedinput, setSavedinput] = useState({firstname:"",
lastname:""});
function ChangeFirst (e) {
savedinput.firstname = e
setSavedinput({...savedinput})
};
function ChangeLast(e) {
savedinput.lastname = e
setSavedinput({...savedinput})
};
return (
<div className="App">
<input type="Text" onChange={event =>
ChangeFirst(event.target.value)}></input>
<input type="Text" onChange={event =>
ChangeLast(event.target.value)}>.
</input>
<h1> hello {savedinput.firstname }{savedinput.lastname} </h1>
</div>
);
}
You can find this working in this link
Related
I am working with Reactjs and nextjs,Right now i am trying to get input type text value but right now i am not getting any value(name is empty during alert), here is my current code
import dynamic from 'next/dynamic';
import React, { FormEventHandler, useRef } from 'react';
import { useEffect, useState } from "react";
import axios from 'axios';
export default function Testform() {
const [state, setState] = useState({ name: '' });
const [Name, setName] = useState('');
const handleChange = (event:any) => setState({...state, name: event.target.value })
const submitHandler: FormEventHandler<HTMLFormElement> = async (event) => {
event.preventDefault();
const name = Name;
alert('name is '+ name);
}
return (
<form className="forms-sample" onSubmit={submitHandler}>
<div className='flex-dvs'>
<div className="form-group">
<h3>Blog title</h3>
<input type="text"
className="form-control"
id="exampleInputName1"
placeholder="Title"
name="name"
value={state.name}
onChange={handleChange}
/>
</div>
</div>
<div className='save-btn text-right'>
<button className='btn btn-primary mr-2'>Save</button>
</div>
</form>
)
}
You are setting the state variable. So use state.name instead of Name
const name = state.name;
I'm trying to put input value into json file, but submit button doesn't work, can you help me with it?
import PcosData from "/data/pcos.json";
import {useEffect} from "react";
import { useState } from "react";
export default function adminPcos() {
// const CreateMePanel = () => {
const [title, setTitle] = useState(PcosData["pcos-first"].title);
const [time, setTime] = useState(PcosData["pcos-first"].time);
const handleSubmit = (e) => {
PcosData["pcos-first"].title = title;
PcosData["pcos-first"].time = time;
}
return (
<div>
<h1>hello world</h1>
{PcosData["pcos-first"].map((pcosdata) => (
<form onSubmit={handleSubmit} key={ pcosdata.id } method="post">
<input type="text" name={title} defaultValue={pcosdata.title} onChange={(e) => setTitle({text: e.target.value})}/>
<input type="text" name={time} defaultValue={pcosdata.time} onChange={(e) => setTime({text: e.target.value})}/>
<input type="submit" value="submit"/>
</form>
))}
</div>
)
}
i checked all of the functions, variables, but didn't find any errors
i want to pass a prop from one(App.jsx) component to other component(form.jsx) in state hooks
App.jsx
import React, {useEffect, useState} from 'react';
import Form from './components/Form';
import Table from './components/Table';
import axios from 'axios';
const App = () => {
const [data, setData] = useState({data:[]});
const [editData, setEditData] = useState([]);
const create = (data) => {
axios.post('http://localhost:5000/info',data).then((res) =>{
getAll();
})
}
useEffect(() =>{
getAll();
},[])
const getAll = () =>{
axios.get("http://localhost:5000/info").then((response) =>{
setData({
data:response.data
})
})
}
const update = event =>{
setEditData(data)
console.log(data); // THIS "data" is the prop that i need to pass to Form.jsx component
}
return (
<div>
<div>
<Form myData={create} editForm={editData} />
</div>
<div>
<Table getData={data} edit={update} />
</div>
</div>
);
};
export default App;
i want that "data" value form App.jsx component as props in this Form.jsx component
Form.jsx
import React, {useState} from 'react';
const Form = (props) => {
const [formData, setFormData] = useState({ Name:'', Age:'', City:''});
const infoChange = e => {
const { name,value} = e.target;
setFormData({
...formData,
[name]: value,
})
}
const infoSubmit = e =>{
e.preventDefault();
let data={
Name:formData.Name,
Age:formData.Age,
City:formData.City
}
props.myData(data);
}
const componentWillReceive = (props) => { // i want the props data here
console.log(props.data); // in class component they use componentWillReceiveRrops ,
} // is there any alternative for function based component to receive props?
return (
<div>
<form onSubmit={infoSubmit} autoComplete="off">
<div>
<label>Name:</label>
<input type="text" onChange={infoChange} name="Name" value={formData.Name} placeholder="Enter Name" />
</div>
<div>
<label>City:</label>
<input type="text" onChange={infoChange} name="City" value={formData.City}
placeholder="Enter City" />
</div>
<div>
<label>Age:</label>
<input type="text" onChange={infoChange} name="Age" value={formData.Age} placeholder="Enter Age" />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
export default Form;
i have commented the area of problem within the code , you can ignore the return () block of code.
Sorry for silly questions but THANKYOU Very Much !!! in advance
Use the following code in Form.jsx, the useEffect will listen the change of props.data and update the value
useEffect(() => {
setFormData(props.data);
},
[props.data]);
For more information, you may check the following answer
https://stackoverflow.com/a/65842783/14674139
I started to learn to react today, and I'm trying to build a super simple calculator, but I'm not familiar with the syntax and basics of reacting yet. No matter how much I'm looking and reading, my code is like this :
import './App.css';
const plusaction = (a, b) => {
alert(a+b);
}
function App() {
return (
<div className="App">
<input type="number" value={plusaction.a}></input>
<input type="number" value={plusaction.b}></input>
<button onClick={plusaction}>Result</button>
</div>
);
}
export default App;
As you can see, it was supposed to be a simple form plus action calculator, but the alert brought me "object undefined", Would you mind fixing my code and explaining what I did wrong? I appreciate any help you can provide.
First you must have a state to save data
after that, you must change your state with onChange function of input
after that, you must read your values from state
function App() {
const [state, setState] = useState({ a: 0, b: 0 });
const plusaction = () => {
alert(state.a + state.b);
};
return (
<div className="App">
<input type="number" value={state.a} onChange={(e) => setState({ ...state, a: e.target.value })} />
<input type="number" value={state.b} onChange={(e) => setState({ ...state, b: e.target.value })} />
<button onClick={plusaction}>Result</button>
</div>
);
}
export default App;
You should use useRef to do this. It will more efficient than useState which will re-render your app each time your number change.
import { useRef } from "react";
function App() {
const a = useRef(0);
const b = useRef(0);
const plusaction = () => {
console.log(a.current.value);
console.log(b.current.value);
alert(parseInt(a.current.value) + parseInt(b.current.value));
};
return (
<div className="App">
<input type="number" ref={a} />
<input type="number" ref={b} />
<button onClick={plusaction}>Result</button>
</div>
);
}
export default App;
you can simply use controlled Input like this :
import {useState} from "react";
function App() {
const [firstVal,setFirstVal] = useState('');
const [secondVal,setSecondVal] = useState('');
const handleShowResult = ()=>{
alert(parseInt(firstVal) + parseInt(secondVal))
}
return (
<div className="App">
<input type="number" value={firstVal} onChange={(e)=>setFirstVal(e.target.value)}></input>
<input type="number" value={secondVal} onChange={(e)=>setSecondVal(e.target.value)}></input>
<button onClick={handleShowResult}>Result</button>
</div>
);
}
export default App;
hope its helpful
You should use state to saving data.
import {useState} from "react";
function App() {
const [firstNumber, setFirstNumber] = useState(0);
const [secondNumber, setSecondNumber] = useState(0);
const plusaction = () => {
alert(firstNumber + secondNumber);
};
return (
<div className="App">
<input type="number" value={firstNumber} onChange={(e) => setFirstNumber(e.target.value)} />
<input type="number" value={secondNumber} onChange={(e) => setSecondNumber(e.target.value)} />
<button onClick={plusaction}>Result</button>
</div>
);
}
Ideally you want to want to store your input values in state. Here I've initialised the input state as an object which will later update with a and b properties containing the values of the inputs.
plusAction (or handleAdd as I've called it here) then just takes the a and b values from the input state and logs the sum to the console.
Give you input elements a name attribute so they can be identified easily.
const { useState } = React;
function Example() {
// Initialise state
const [ input, setInput ] = useState({});
// Destructure the a and b properties from
// the state and sum them
function handleAdd() {
const { a, b } = input;
console.log(a + b);
}
// The onChange listener is attached to the
// parent container so we need to check to see
// if the changed element is an input
function handleChange(e) {
if (e.target.matches('input')) {
// Destructure the name and value from the input
const { name, value } = e.target;
// Set the new input state by copying it, and
// updating either the a or b property we get from
// the name attribute, and then setting its value
// Note: the type of the value from an input will
// always be a string, so you need to coerce it to
// a number first
setInput({ ...input, [name]: Number(value) });
}
}
// The input elements store the value of the
// corresponding state property
return (
<div onChange={handleChange}>
<input name="a" type="number" value={input.a} />
<input name="b" type="number" value={input.b} />
<button onClick={handleAdd}>Result</button>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Additional documentation
Destructuring assignment
Spread syntax
matches
This is a React form. I have been trying to display Hello {firstName} {lastName} after the user gives the inputs and clicks the submit button . However, it is not recording the inputs properly and not displaying it correctly after the submit button is clicked. Please help!!!
import React, { useState } from 'react';
function App() {
const [newName, setNewName] = useState({
fName: '',
lName: ''
});
const [fullName, setFullName] = useState(newName);
function handleOnSubmit(event) {
console.log(newName);
setFullName(newName);
event.preventDefault();
}
function handleOnChange(event) {
console.log(newName);
var { value, name } = event.target;
setNewName((prevValue) => {
if (name === 'fName')
return {
fName: value,
lName: prevValue.lName
};
else
return {
fName: prevValue.fName,
lName: value
};
});
}
return (
<div className='container'>
<h1>
Hello {fullName.fName} {fullName.lName}
</h1>
<form onSubmit={handleOnSubmit}>
<input
name='fName'
placeholder='First Name'
onChange={handleOnChange}
value={fullName.fName}
/>
<input
name='lName'
placeholder='Last Name'
onChange={handleOnChange}
value={fullName.lName}
/>
<button type='submit'>Submit</button>
</form>
</div>
);
}
export default App;
The problem was event handling on the input boxes. In value you binded fullName.fName and fullName.lName , but onChange you are updating the state of newName and the state of the fullName is only getting changed when you click submit . Please update the form code as below. It should work for you !
<form onSubmit={handleOnSubmit}>
<input
name="fName"
placeholder="First Name"
onChange={handleOnChange}
value={newName.fName}
/>
<input
name="lName"
placeholder="Last Name"
onChange={handleOnChange}
value={newName.lName}
/>
<button type="submit">Submit</button>
</form>
Try using this:
We are going to create an Input custom hook.
useInput.js file
//input custom hook
import { useState } from "react";
function useInput(initialValue = "") {
const [value, setValue] = useState(initialValue);
const reset = () => {
setValue(initialValue);
};
const bind = {
value,
onChange: (e) => setValue(e.target.value),
};
return [value, bind, reset];
}
export default useInput;
This is how you can use this Input custom hook:
import React from "react";
import useInput from "../hooks/useInput";
function Test() {
const [firstName, bindFirstName, resetFirstName] = useInput("");
const [lastName, bindLastName, resetLastName] = useInput("");
const handleSubmit = (e) => {
e.preventDefault();
alert(`hello ${firstName} ${lastName}`); // you can change this as per your requirement
resetFirstName();
resetLastName();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" {...bindFirstName} />
<input type="text" {...bindLastName} />
<button value="submit" type="submit">
Submit
</button>
</form>
</div>
);
}
export default Test;