How to get textarea data with useState() - reactjs

I have read page after page and I am not sure what I am doing wrong. My useState works with my other inputs. I am unable to get it to work with my textarea.
Also, what would be the best way to use my data in another component?
import React, { useState } from "react";
const OrderItems = () => {
const [commentText,setCommentText] = useState("")
const onSubmit = (data) => {
console.log(data.commentText);
}
return (
<>
<form id="myForm" onSubmit={handleSubmit(onSubmit)} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information</label>
<textarea
name = "commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value = {commentText}
onChange={e => setCommentText(e.target.value)}
>
</textarea>
</div>
</form>
<button type = "submit" form ="myForm" className="btn_submit" alt = "submit Checkout">
<a href ="/cart/preview"/>
<img src = ""/>
</button>
</>
)
}

You are initializing state outside the function, Please do it like this:
Also, You are logging the wrong state inside onSubmit.
import React, { useState } from "react";
const OrderItems = () => {
const [commentText,setCommentText] = useState("")
const handleSubmit = (evt) => {
evt.preventDefault();
console.log(commentText);
}
return (
<>
<form id="myForm" onSubmit={handleSubmit} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information</label>
<textarea
name = "commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value = {commentText}
onChange={e => setCommentText(e.target.value)}
>
</textarea>
<input type = "submit" value="Submit" className="btn_submit" alt = "submit Checkout"/>
</div>
</form>
</>
)
}
To use the data in another component: If it is a child component pass it as props. Else use state management tools like context or redux.
Also, for routing, I would recommend using React Router. Refer here.

Some things to keep in mind:
import React, { useState } from "react";
const OrderItems = () => {
// Always initialise state inside the component
const [commentText,setCommentText] = useState("")
const handleOnSubmit = event => {
event.preventDefault();
console.log(commentText);
}
return (
// onSubmit should just be a reference to handleOnSubmit
<form id="myForm" onSubmit={handleOnSubmit} >
<div>
<label
htmlFor="CommentsOrAdditionalInformation">Comments or Additional Information
</label>
// You can self-close the textarea tag
<textarea
name="commentTextArea"
type="text"
id="CommentsOrAdditionalInformation"
value={commentText}
onChange={e => setCommentText(e.target.value)}
/>
</div>
// Put the button inside the form
<button type = "submit" form ="myForm" className="btn_submit" alt="submit Checkout">
<a href ="/cart/preview"/>
<img src = ""/>
</button>
</form>
);
}

Related

Onchange in input field is not working while editing a form

I am developing a small application in react, in which I have an edit option. On clicking the edit button, it will load the existing data and allows the user to edit any of the fields and submit.
Fetching the data and loading it in a form are working fine, but when I edit a textbox, the value changes to the existing fetched value, and it is not allowing me to hold the edited value.
Please note, the problem is with editing the input in a form not in submitting. Below is the edit component that I am using.
mport { useState, useEffect } from 'react';
import { json, Link } from 'react-router-dom';
import { useParams } from 'react-router-dom';
const EditTask = ({ onEdit }) => {
const [text, setText] = useState('');
const [day, setDay] = useState('');
const [reminder, setReminder] = useState(false);
const params = useParams();
useEffect(() => {
fetchTask();
});
const fetchTask = async () => {
const res = await fetch(`http://localhost:5000/tasks/${params.id}`);
const data = await res.json();
setText(data.text);
setDay(data.day);
setReminder(data.reminder);
};
const onSubmit = async (e) => {
e.preventdefault();
if (!text) {
alert('Please enter task name');
return;
}
onEdit({ text, day, reminder });
setText('');
setDay('');
setReminder(false);
};
const handleChange = ({ target }) => {
console.log(target.value); // displaying the input value
setText(target.value); // changes to existing value not the one I entered
};
return (
<form className="add-form" onSubmit={onSubmit}>
<div className="form-control">
<label>Task</label>
<input
id="AddTask"
type="text"
placeholder="Add Task"
value={text}
onChange={handleChange}
/>
</div>
<div className="form-control">
<label>Date & Time</label>
<input
id="Date"
type="text"
placeholder="Date & Time"
value={day}
onChange={(e) => setDay(e.target.value)}
/>
</div>
<div className="form-control form-control-check">
<label>Set Reminder</label>
<input
id="Reminder"
type="checkbox"
checked={reminder}
value={reminder}
onChange={(e) => setReminder(e.currentTarget.checked)}
/>
</div>
<input className="btn btn-block" type="submit" value="Save Task" />
<Link to="/">Home</Link>
</form>
);
};
export default EditTask;
Can someone explain what I am missing here? Happy to share other information if needed.
Expecting the input fields to get the value entered and submitting.
You missed adding dependency to useEffect
Yours
useEffect(() => {
fetchTask()
}
)
Should be changed
useEffect(()=>{
fetchTask()
}, [])
becasue of this, fetchTask is occured when view is re-rendered.

Get id from one form out of multiple forms? (React)

I am trying send only one of my form's id to my handleSubmit function in react. My forms are created via a map function, which creates a form for each data enter from my DB. My handleSubmit function currently take in an event and outputs it to the console log. When running the code, I get all of my id's instead of one. Any help?
Here is my code:
import React, { useRef, useState } from 'react';
export const Movie = ({listOfReviews}) =>{
const handleSubmit = (event) => {
console.log(event)
}
return (
<>
<h1>Your reviews:</h1>
{listOfReviews.map(review =>{
return(
<form onSubmit={handleSubmit(review.id)}>
<label>
Movieid:{review.movieid}
<input type="text" value={review.id} readonly="readonly" ></input>
<input type="text" value={review.comment}></input>
<input type="submit" value="Delete"></input>
</label>
</form>
)
})}
</>
)
}
You have a simple error in your onSubmit callback. Instead of calling handleSubmit in the callback prop, you should instead define an inline function that calls handleSubmit.
Like this:
<form onSubmit={() => handleSubmit(review.id)}>
Full code:
import React, { useRef, useState } from 'react';
export const Movie = ({ listOfReviews }) => {
const handleSubmit = (id) => {
console.log(id);
};
return (
<>
<h1>Your reviews:</h1>
{listOfReviews.map((review) => {
return (
<form onSubmit={() => handleSubmit(review.id)}>
<label>
Movieid:{review.movieid}
<input type="text" value={review.id} readonly="readonly"></input>
<input type="text" value={review.comment}></input>
<input type="submit" value="Delete"></input>
</label>
</form>
);
})}
</>
);
};

I’m trying to save data on the database but it is saving each input change

import React, {useState, useEffect} from 'react'
import { NoMoralisContextProviderError } from 'react-moralis';
import './css/createpost.css'
import { useMoralis } from "react-moralis";
function CreatePost() {
const [title, setTitle] = useState("")
const [content, setContent] = useState("")
const { Moralis, isInitialized } = useMoralis();
const createNewPost = (e, title, content) => {
e.preventDefault()
const newPost = Moralis.Object.extend("Posts");
const post = new newPost();
post.set("title", title);
post.set("content", content);
post.save();
return post;
}
return (
<div>
<div>
<form action="#" className="createpost">
<div class="data">
<label>Title</label>
<input type="text" required onChange={(e) => setTitle(e.target.value)}/>
</div>
<div class="data">
<label>Content</label>
<input type="text" required onChange={(e) => setContent(e.target.value)}/>
</div>
<div class="btn">
<div class="inner"></div>
<button type="submit" onClick={createNewPost(e, title, content)}>Submit Post</button>
</div>
</form>
</div>
</div>
)
}
export default CreatePost
I’m trying to save the data to the database, but after each input change it is saved. So if I type “hello” it saves “h”, “he”, “hel”, “hell”, “hello” and I would like it to just save hello once. Not each input change. Can someone help me fix this issue?
I'm trying to save this to moralis database, but i think the error is that the function is called multiple times.
Wrap your handler to arrow function
<button type="submit" onClick={() => createNewPost(e, title, content)}>Submit Post</button>

How to do validation using useRef()

How do I validate input box value using useRef .
Initial validation is not required once user clicks on input box and comes out then it should validate if input box is empty it should show input box cannot be empty.
Codesandbox Link
code i tried. using onBlur
export default function App() {
const name = React.useRef("");
const nameBlurData = (name) => {
console.log("name", name);
};
return (
<div className="App">
<form>
<input
onBlur={() => nameBlurData(name.current.value)}
type="text"
ref={name}
placeholder="Enter First Name"
/>
// show error message here
</form>
</div>
);
}
You can use "useRef" to validate the value of an input field.
No need to use "useState".
Below code is a basic implementation of OP's question
You can replace the "console.log" with your alert component.
import { useRef } from "react";
const ComponentA = () => {
const emailRef = useRef(null);
const passwordRef = useRef(null);
const onBlurHandler = (refInput) => {
if (refInput.current?.value === "") {
console.log(`${refInput.current.name} is empty!`);
}
}
return (
<form>
<input ref={emailRef} onBlur={onBlurHandler.bind(this, emailRef)} />
<input ref={passwordRef} onBlur={onBlurHandler.bind(this, passwordRef)} />
<form/>
)
}
Link to "useRef"
Note: Not tested, code typed directly to SO's RTE
You can use a local state and conditionally render an error message like this:
const [isValid, setIsValid] = useState(true)
const nameBlurData = (name) => {
setIsValid(!!name);
};
return (
<div className="App">
<form>
<input
onBlur={() => nameBlurData(name.current.value)}
type="text"
ref={name}
placeholder="Enter First Name"
/>
{!isValid && <span> input must not be empty </span> }
</form>
Note that you don't really need a ref in this case, you can just use the event object like:
onBlur={(event) => nameBlurData(event.target.value)}
You need to use useState hook to update the value of the name property. Using ref is not ideal here.
Live demo https://stackblitz.com/edit/react-apqj86?devtoolsheight=33&file=src/App.js
import React, { useState } from 'react';
export default function App() {
const [name, setName] = useState('');
const [hasError, setError] = useState(false);
const nameBlurData = () => {
if (name.trim() === '') {
setError(true);
return;
}
setError(false);
};
return (
<div className="App">
<form>
<input
onBlur={nameBlurData}
type="text"
value={name}
onChange={e => setName(e.target.value)}
placeholder="Enter First Name"
/>
{hasError ? <p style={{ color: 'red' }}>Name is required</p> : null}
</form>
</div>
);
}

Trying to bind submit and save to localStorage

Here my App.js code, I am trying to bind and capture the "handlesubmit" function, and then append to an empty list which will be populated. Thanks.
import React from 'react';
const App = () => {
const [songs, setSongs] = React.useState([]);
React.useEffect(() => {
const data = localStorage.getItem('songs');
if (!data) { }
setSongs(JSON.parse(data));
}, []);
React.useEffect(() => {
localStorage.setItem('songs', JSON.stringify(songs));
});
const handleSubmit = data => {
setSongs([data]);
}
return (
<main>
<h1>Music Editor</h1>
<form onSubmit={this.props.handleSubmit(this.handleSubmit.bind(this))} autoComplete="false">
<label for="title">Title:</label>
<input type="text" id="title" name="title" placeholder="Type title/name of song" value="" />
<input type="submit" value="Add song" />
</form>
</main>
);
}
export default App;
The explanation is commented in the code itself.
Here is the codesandbox link to see the App working.
import React from 'react';
const App = () => {
const [songs, setSongs] = React.useState([]);
// use another state for song title
const [songTitle, setSongTitle] = React.useState('');
React.useEffect(() => {
const data = localStorage.getItem('songs');
// only update the state when the data persists
if (data) setSongs(JSON.parse(data));
}, []);
// update the localStorage whenever the songs array changes
React.useEffect(() => {
localStorage.setItem('songs', JSON.stringify(songs));
}, [songs]);
// inside the functional component, there is no "this" keyword
const handleSubmit = (event) => {
event.preventDefault();
// append the new song title with the old one
setSongs([
...songs,
songTitle
]);
}
return (
<main>
<h1>Music Editor</h1>
<form onSubmit={handleSubmit} autoComplete="false">
<label htmlFor="title">Title:</label>
<input
type="text"
id="title"
name="title"
placeholder="Type title/name of song"
value={songTitle}
onChange={e => setSongTitle(e.target.value)}
/>
<input type="submit" value="Add song" />
</form>
</main>
);
}
export default App;

Resources