Display user input value upon submit in react - reactjs

I want the user to input some text, click submit and the text will be displayed below.
I was able to get the input text as a whole, and print it in console. But I don't know how to display the text.
Here's my code:
https://codesandbox.io/s/ecstatic-curie-ej6og?file=/src/App.js
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [enteredText, setEnteredText] = useState("");
const textChangeHandler = (i) => {
setEnteredText(i.target.value);
//console.log(i.target.value);
};
const submitHandler = (event) => {
event.preventDefault();
const x = enteredText;
console.log(x);
setEnteredText("");
};
return (
<div className="App">
<h1>Get user input</h1>
<form onSubmit={submitHandler}>
<input
placeholder="type something"
type="text"
value={enteredText}
onChange={textChangeHandler}
/>
<button type="submit" >
Submit
</button>
</form>
<p>You just typed: {x}</p> // This is wrong. x is out of scope. But i'm not sure how to write this line.
</div>
);
}

You can use an additional state variable to store the "submitted text". You would update that new state variable with the text from the enteredText state variable before emptying it. You could also make sure the "submitted text" has a value before displaying it.
I am including code that does what I described, but you can also try implementing it on your own before looking at it:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [enteredText, setEnteredText] = useState("");
const [submittedText, setSubmittedText] = useState(null);
const textChangeHandler = (i) => {
setEnteredText(i.target.value);
//console.log(i.target.value);
};
const submitHandler = (event) => {
event.preventDefault();
setSubmittedText(enteredText);
setEnteredText("");
};
return (
<div className="App">
<h1>Get user input</h1>
<form onSubmit={submitHandler}>
<input
placeholder="type something"
type="text"
value={enteredText}
onChange={textChangeHandler}
/>
<button type="submit" >
Submit
</button>
</form>
{submittedText && (<p>You just typed: {submittedText}</p>)}
</div>
);
}

Related

React onClick button is not triggering the function

I am developing an chrome extension where i need to authentication user but a very simple onClick button which calls a function is not working
this is the simple code where i want to show info on console when button is clicked
import React, { useState } from 'react';
const Login = () => {
const [user, setuser] = useState("");
const handleSubmit = (data) => {
data.preventDefault();
console.log("usernae: ");
console.log("Data: ", data.target);
}
const getInputValue = (event) => {
console.log(event.target.value)
// Select input element and get its value
console.log("I am heresdfg")
// let inputVal = document.getElementsByClassName("usernameInputField")[0].value;
// Display the value
// alert(inputVal);
}
return (
<div
id="login-form">
<p>
<div className='form'>
</div>
<input type="text"
id="username"
name="username"
className='usernameInputField'
value={user}
onChange={(event => setuser(event.target.value))}
placeholder="Username" required />
</p>
<p>
<button onClick={getInputValue} type="button" id="login">button</button>
</p>
</div>
);
};
export default Login;
It seems like you want the input value value inside the event handler if I'm not wrong, you can get it from the state - user as
const getInputValue = (event) => {
console.log(user)
}
as the event would be button's you wouldn't get the value of input from it's event and it is not required too as it's already in the react's state ....
Example:
const {useState} = React;
const App = () => {
const [name, setName] = useState("");
const submitHandler = () => {
console.log(name)
}
return (
<div>
Name: <input type="text" value={name} onChange={(e)=>setName(e.target.value)}/>
<button onClick={submitHandler}>Submit</button>
</div>
);
};
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App/>
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
In the getInputValue function event is pointing to the button.
Change the event.target.value to user if you want to print the text into the console.
Here's the codesandbox.
If you don't want to use the value from useState then you can also check useRef hook which works in a similar way.

how to get data from input form in React js by clicking submit button and create a div element that get all data user input. {.map() Multiple states}

I'd like to create div with data getting from user input by clicking btn submit, But I don't know how. I am new in react js.
This is my App.js file:
import './App.css';
import './RegisterApp.css'
import RegisterApp from './Components/RegisterApp';
function App() {
return (
<div className="App">
<RegisterApp />
</div>
);
}
export default App;
and this is my component file RegisterApp.js:
import React, {useState} from 'react'
function RegisterApp() {
const [name, setName] = useState('Khun Neary')
const [position, setPosition] = useState('Designer')
const [list, setList] = useState({name, position})
const formSubmit = (e) => {
e.preventDefault()
setList(...list, name)
setList(...list, position)
console.log(list);
}
return (
<div className='container'>
<form className='form-box' onSubmit={formSubmit}>
<button>Upload Profile</button>
<input
type="text"
placeholder='Name...'
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="text"
placeholder='Position...'
value={position}
onChange={(e) => setPosition(e.target.value)}
/>
<button>Submit</button>
</form>
<div className='register-box'>
<div className='sub-reg-box'>
<div className='img-box'></div>
<div className='detail-box'>
<h2>{name}</h2>
<h4>{position}</h4>
</div>
</div>
</div>
</div>
)
}
export default RegisterApp
enter image description here
I'd like to create div element after I click submit btn and display all the data get from input by user.
add type="submit" to button
<button type="submit">Submit</button>
then update the list state
const formSubmit = (e) => {
setList( {...list, name, position })
}
you won't see the update to the list immediately since setState in asynchronous. But to check that, you can use useEffect
useEffect(() => {
console.log(list)
},[list])
You don't need to "get" the data. You already have it in the variables name and position. You should create an onClick handler for the button that uses these values.
Note that setList() is misnamed. You should use an object here. In fact, you can get rid of list and setList because you already have name, setName, position and setPosition. You don't need both.

whenever I click add my page refreshes so all the value in array resets

Please give me solution I am creating a app similar to Google keep.
As soon as I click add button is add to array after that it refreshes the page and array value resets
Here's my Code
import React, { useState } from "react";
function CreateArea() {
const [title1, setTitle1] = useState([]);
const [note1, setNote1] = useState([]);
function Changed(event) {
const a = event.target.name;
// const b=event.target.name;
if (a === "title") {
// console.log("hello")
setTitle1(event.target.value);
} else {
// console.log("note")
setNote1(event.target.value);
}
}
function addNote() {
// setTitle1((prevValue) => {
// return [...prevValue, title1]
// })
// console.log(titleCont)
setNote1("");
setTitle1("");
console.log(title1);
}
return (
<div>
<form>
<input
name="title"
onChange={Changed}
placeholder="Title"
// value={title1}
/>
<textarea
name="content"
onChange={Changed}
placeholder="Take a note..."
// value={note1}
rows="3"
/>
<button onClick={addNote}>Add</button>
</form>
</div>
);
}
export default CreateArea;
IDK if this code if sufficient or not if need more of my code plz tell me i will add more
Change,
<button onClick={addNote}>Add</button>
To:
<button type="button" onClick={addNote}> Add </button>
If we don't use type="button" , browser will set it to 'reset' or 'submit' which cause to page reload.
Ref: https://stackoverflow.com/a/20760450/7785337
Working example:
You need to create another piece of state to store the notes.
import React, { useState } from "react";
function CreateArea() {
const [title1, setTitle1] = useState(""); // changes
const [note1, setNote1] = useState(""); // changes
const [notes, setNotes] = useState([]); // changes
function Changed(event) {
const a = event.target.name;
// const b=event.target.name;
if (a === "title") {
// console.log("hello")
setTitle1(event.target.value);
} else {
// console.log("note")
setNote1(event.target.value);
}
}
function addNote() {
setNotes([...notes,{title:title1,text:note1}]) // changes
setNote1("");
setTitle1("");
console.log(title1);
}
return (
<div>
<form>
<input
name="title"
onChange={Changed}
placeholder="Title"
// value={title1}
/>
<textarea
name="content"
onChange={Changed}
placeholder="Take a note..."
// value={note1}
rows="3"
/>
<button type="button" onClick={addNote}>Add</button>// changes
</form>
</div>
);
}
export default CreateArea;
By default button is type submit. You can pass to the button type="button" or pass event.preventDefault() in your function.I prefer this.
function addNote(event) {
event.preventDefault();
// ... rest of the code
}

React.js setState not getting update wiith onclick

This is my sample code, it's very basic i just want to console fname once submit is clicked.
When i pressed first time i get an empty line but when pressed second time the button i get some empty value. I am attaching the screenshot for the console.
I dont want to change my code to a class and use some method to get the value in console.
screenshot for console output
import React,{useState} from 'react'
export const anyComponent = () => {
const [fname, setFname] = useState('')
const submit = (event) =>{
setFname({fname: [event.target.value] })
console.log(fname)
}
return(
<div>
<input name="fname" type="text" placeholder="Enter your First Name" />
<button onClick={submit}>Submit</button>
</div>
)
}
From MDN Docs:
The target property of the Event interface is a reference to the object onto which the event was dispatched.
In your case, event.target would point to the button and not input.
What you need is a reference to the input, you can use useRef hook for it like this
import React, { useState, useRef } from "react";
export default anyComponent = () => {
const inputEl = useRef(null);
const [fname, setFname] = useState("");
const submit = event => {
setFname({ fname: [inputEl.current.value] });
};
console.log(fname);
return (
<div>
<input
name="fname"
ref={inputEl}
type="text"
placeholder="Enter your First Name"
/>
<button onClick={submit}>Submit</button>
</div>
);
};
Also, setState is asynchronous, that's why you wouldn't see the result in the console just after calling setFname. However you'd see the updated fName in console on the next render, that's why I've moved it out of the submit.
Without useRef
Alternatively, you can add onChange handler on input and update the state fname from there
function App(){
const [fname, setFname] = useState("");
const submit = () => {
console.log(fname);
};
const handleChange = ev => {
setFname({ fname: [ev.target.value] });
}
return (
<div>
<input
name="fname"
onChange={handleChange}
type="text"
placeholder="Enter your First Name"
/>
<button onClick={submit}>Submit</button>
</div>
);
};
Your console log should be outside submit method. Or log event.target.value instead fname.

cannot clear form field with functional react hook in reactjs

The code below works fine by submit a post message. now i want to clear the message input form on form submission but cannot get it to work. I have tried the following 3 options but yet no luck.
1.)
function clearState() {
message('');
}
// pass the clear state function on form submission
clearState();
2.) Clear form by referencing the form id
document.getElementById('my_form').reset();
3.) using event target reset
event.target.reset();
here is the full code.
import React, { useState, useRef, useEffect } from "react";
export default function App(props) {
const [message, setMessage] = useState("");
const [messages, setMessages] = useState([]);
const currentDate = new Date();
useEffect(() => {
// fetch content axio or ajax
}, []);
function clearState() {
message('');
}
function handleChange(event) {
setMessage(event.target.value);
}
function handleSubmit(event) {;
event.preventDefault();
const newMessages = messages;
const data = { message: message, date: new Date() };
setMessages(newMessages.concat([data]));
//clear all form field based on form id
clearState();
//document.getElementById('my_form').reset();
//event.target.reset();
}
return (
<React.Fragment>
<div className="chat_container">
{messages.map((m, e) => (
<div key={e}>
<div className="chat_message">
chat: {m.message} ---{m.date.toLocaleTimeString()}
</div>
</div>
))}
</div>
<div className="myFooter">
<form id"my_form" onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={message} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
</React.Fragment>
);
}

Resources