/**
Make sure we keep the same functionality, without causing a re-render
on every keypress when typing in the input.
*/
import React, { useState } from "react";
export const Example: React.FC = () => {
const [userInput, setUserInput] = useState("");
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
setUserInput(event.target.value);
}
console.log("Example renders");
return (
<>
<h1>Send us some feedback</h1>
<div>
<input type="text" onChange={handleChange} value={userInput} />
<button
type="submit"
onClick={() => {
alert(userInput);
}}
>
Submit
</button>
</div>
</>
);
};
Related
In the below, I have verified that setNewItem works, however items doesn't get updated so there must be an issue with the function handleSubmit. What is going wrong here?
import "./styles.css";
import React, {useState, useEffect} from 'react';
export default function App() {
const [items, setItems] = useState(['first item']);
const [newItem, setNewItem] = useState("");
const handleSubmit = (event, newItem, items) => {
event.preventDefault();
setItems([ newItem, ...items]);
};
const handleChange = (event) => {
setNewItem(event.target.value);
}
return (
<div>
<form>
<input type="text"
value={newItem}
onChange={handleChange}
/>
<input type="submit"
value="submit"
onSubmit={handleSubmit}
/>
</form>
<ul>
{items.map( (i) => {
return(<li>{i}</li>)
})}
</ul>
</div>
);
}
https://codesandbox.io/s/new?file=/src/App.js:0-797
try this 👇
import "./styles.css";
import React, { useState, useEffect } from "react";
export default function App() {
const [items, setItems] = useState(["first item"]);
const [newItem, setNewItem] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
console.log("here");
setItems([newItem, ...items]);
};
const handleChange = (event) => {
setNewItem(event.target.value);
};
return (
<div>
<form>
<input type="text" value={newItem} onChange={handleChange} />
<input type="button" value="submit" onClick={handleSubmit} />
</form>
<ul>
{items.map((i) => {
return <li>{i}</li>;
})}
</ul>
</div>
);
}
You need to change and try this.
const handleSubmit = (event) => {
event.preventDefault();
setItems([ newItem, ...items]);
};
...
...
...
<input type="submit"
value="submit"
onSubmit={event => handleSubmit(event)}
/>
I create a simple page called lucky number
pages/lucky.js
import finder from '../../hooks/use-finder'
import NumberForm from '../components/number-form'
export default function LuckyNumber() {
const { data } = finder(number)
console.log(data)
return (
<>
<h1>Lucky Number</h1>
<NumberForm />
</>
)
}
export default function NumberForm() {
return (
<>
<form>
<label>
Number:
<input type="text" name="number" />
</label>
<input type="submit" value="Submit" />
</form>
</>
)
}
where NumberForm is a form where user can just input a number ex: 12345. Once use submits the form, I want to pass that number to my hook in the page finder(number) so I can check to see if that number is in my lucky list of numbers.
How can I pass the number that user submits to the page?
I think you can use parent state and send the setState to the child to update it i.e.
pages/lucky.js
import React, { useState } from 'react'
import finder from '../../hooks/use-finder'
import NumberForm from '../components/number-form'
export default function LuckyNumber() {
const [number, setnumber] = useState(0);
const { data } = finder(number)
console.log(data)
return (
<>
<h1>Lucky Number</h1>
<NumberForm onChange={setnumber} />
</>
)
}
export default function NumberForm({ onChange }) {
const [number, setnumber] = useState(0);
const handleChange = (event)=>{
setNumber(event?.target?.value)
}
const handleSubmit = (event)=>{
event.preventDefault();
onChange(number)
}
return (
<>
<form>
<label>
Number:
<input type="text" name="number" value={number} onChange={ handleChange } />
</label>
<input type="submit" value="Submit" onClick={ handleSubmit } />
</form>
</>
)
}
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>
);
}
i'd like to simplify form creation avoiding to write for each fied value={} and onChange={} using a custom hook.
this is my code:
https://codesandbox.io/s/busy-noether-pql8x?file=/src/App.js
the problem is that, each time i press the button, the state is cleaned except for the field i've currently edited
import React, { useState } from "react";
import "./styles.css";
const useFormField = (initialValue) => {
const [values, setValues] = React.useState(initialValue);
const onChange = React.useCallback((e) => {
const name = e.target.name;
const value = e.target.value;
setValues( (prevValues) => ({...prevValues,[name]:value}));
}, []);
return { values, onChange };
};
export default function App() {
//hoot to simplify the code,
const {values,onChange} = useFormField({
Salary: "",
Email: ""
})
const onCreateUser = () => {
console.log(values);
};
return (
<div className="App">
<form>
<label htmlFor="Email">Email: </label>
<input name="Email" onChange={onChange} />
<label htmlFor="Email">Salary: </label>
<input name="Salary" onChange={onChange} />
<button type="button" onClick={onCreateUser}>
Send
</button>
</form>
</div>
);
}
I want to make a submit form by Redux-Form which has a image upload field along with other text fields. I have tried the following approach for image upload and the problem is whenever I try to upload image the form gets re-rendered. How can I do it in a proper way? And another thing is How can I send entire form data (including uploaded image) to Back end? I have used here react,redux-form and material-ui
<Box className={classes.controlTitle}>
Upload Organization Logo
</Box>
<Field
name="logo"
type="file"
component={renderField}
placeholder="Upload your organization logo"
className={classes.field}
/>
I suggest using something like react-uploady. It takes care of the file upload for you and you can use any form/components/ui libraries with it:
import React, { useState, useCallback, useMemo, forwardRef } from "react";
import styled, { css } from "styled-components";
import Uploady, {
useBatchAddListener,
useBatchFinishListener,
useUploadyContext
} from "#rpldy/uploady";
import { asUploadButton } from "#rpldy/upload-button";
const MyUploadField = asUploadButton(
forwardRef(({ onChange, ...props }, ref) => {
const [text, setText] = useState("Select file");
useBatchAddListener((batch) => {
setText(batch.items[0].file.name);
onChange(batch.items[0].file.name);
});
useBatchFinishListener(() => {
setText("Select file");
onChange(null);
});
return (
<div {...props} ref={ref} id="form-upload-button" title={text}>
{text}
</div>
);
})
);
const MyForm = () => {
const [fields, setFields] = useState({});
const [fileName, setFileName] = useState(null);
const uploadyContext = useUploadyContext();
const onSubmit = useCallback(() => {
uploadyContext.processPending({ params: fields });
}, [fields, uploadyContext]);
const onFieldChange = useCallback(
(e) => {
setFields({
...fields,
[e.currentTarget.id]: e.currentTarget.value
});
},
[fields, setFields]
);
const buttonExtraProps = useMemo(
() => ({
onChange: setFileName
}),
[setFileName]
);
return (
<Form>
<MyUploadField autoUpload={false} extraProps={buttonExtraProps} />
<br />
<input
onChange={onFieldChange}
id="field-name"
type="text"
placeholder="your name"
/>
<br />
<input
onChange={onFieldChange}
id="field-age"
type="number"
placeholder="your age"
/>
<br />
<button>
id="form-submit"
type="button"
onClick={onSubmit}
disabled={!fileName}
>
Submit Form
</button>
</Form>
);
};
export default function App() {
return (
<div className="App">
<Uploady
clearPendingOnAdd
destination={{ url: "[upload-url]" }}
multiple={false}
>
<MyForm />
</Uploady>
</div>
);
}
You can check out this sandbox for a complete example.