Handle Change of FormControl React hooks - javascript

This is the example of Textarea where i could not able to set the state value in form-control,..
i could not able to save the state value ,
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Control className="textarea"
value={selectDesc}
as="textarea"
rows={7}
onChange={(event)=>setSelectDesc(event.target.value)}>
</Form.Control> </Form.Group>
outout of the screen ,..

This is an example on how you could achieve this (I used an <input> tag but this would have the same result for a <Form /> from react-bootstrap):
import { useState } from "react"; // import useState
export default function App() {
const [name, setName] = useState(""); // useState hook
// handle change event
const handleChange = (e) => {
e.preventDefault(); // prevent the default action
setName(e.target.value); // set name to e.target.value (event)
};
// render
return (
<div>
<input value={name} type="text" onChange={handleChange}></input>
<p>{name}</p>
</div>
);
}
I made a handler function to make the code a bit cleaner, don't forget to prevent the default action and set the value.
This would be the result using react-bootstrap
import { useState } from "react"; // import useState
import { Form } from "react-bootstrap";
export default function App() {
const [name, setName] = useState(""); // useState hook
// handle change event
const handleChange = (e) => {
e.preventDefault(); // prevent the default action
setName(e.target.value); // set name to e.target.value (event)
};
// render
return (
<div>
<Form>
<Form.Group>
<Form.Control
value={name}
type="text"
onChange={handleChange}
></Form.Control>
</Form.Group>
</Form>
<p>{name}</p>
</div>
);
}
Check out my sandbox here

Related

validate a form in the parent component react

I have a two inputs in my child component, I would like to pass the event of the inputs to my parent component. In the parent component I have a function which will handle the submission. I have the two useState in the parent component, just in case I need to use it in the future in other condition to ensure the user is logged in. I am wondering how to achieve this ? or am I taking the wrong approach with having the usestates in my parent component ?
import { useState } from "react";
import Child from './Child'
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
const loginhandler = ()=>{
if (!login && !password){
console.log("alert error")
} else {
console.log('you are logged in')
}
}
return (
<>
<Child/>
</>
);
}
import { useState } from "react";
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
return (
<>
<input
placeholder="Id"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
<input
placeholder="Password"
value={password}
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
</>
);
}
you can pass function like this:
const setParentState = (val) => setLogin;
how do you pass this function to the child component:
<Child setParentPassword={setParentState} />
this way you can use the child components variables and use or set it in parent state
Flow should be like this :
import { useState } from "react";
import Child from './Child'
import "./styles.css";
export default function Parent() {
const [login, setLogin] = useState(null);
const [password, setPassword] = useState(null);
const loginhandler = ()=>{
//your logic will goes here
if (!login && !password){
console.log("alert error")
} else {
console.log('you are logged in')
}
}
return (
<>
<Child
loginhandler={loginhandler}
setLogin={setLogin}
setPassword={setPassword}
/>
</>
);
}
import { useState } from "react";
import "./styles.css";
export default function Child({loginhandler, setLogin, setPassword}) {
return (
<>
<input
placeholder="Id"
value={login}
onChange={(e) => setLogin(e.target.value)}
/>
<input
placeholder="Password"
value={password}
type="password"
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={loginhandler}>LOGIN</button>
</>
);
}

React custom input passing props to parent functional component while using custom hooks

Am new to react and i have a custom input where am handling the value and input handler via a custom hook but would like to get the value and the input handler to the parent component using the custom input but am stuck on how to achieve this.
I have written the following code.
On the custom hook
import {useReducer} from "react";
const INITAL_STATE = {value:'',valid:false,pristine:true, error:''}
const REDUCER_ACTIONS = { input:"INPUT", blur:"BLUR"}
const reducer = (state,action)=>{
if (action.type === REDUCER_ACTIONS.input){
return {...state, value: action.value}
}
if (action.type === REDUCER_ACTIONS.blur){
return {...state, pristine: false}
}
return INITAL_STATE;
}
const useForm = () => {
const [inputState, dispatch] = useReducer(reducer,INITAL_STATE)
const onBlurHandler = (event) => {
dispatch({type:REDUCER_ACTIONS.blur});
}
const onInputHandler = (event) => {
dispatch({type:REDUCER_ACTIONS.input,value:event.target.value})
}
return {
...inputState,
onBlurHandler,
onInputHandler
}
};
export default useForm;
And for my custom input i have
import useForm from "../../hooks/use-form";
const CustomInput = (props) => {
const {value, onInputHandler, onBlurHandler} = useForm(); //uses custom hook
return <>
<label htmlFor={props.id}>{props.label}</label>
<input value={value} onBlur={onBlurHandler} onInput={onInputHandler}
{...props} />
</>
}
export default CustomInput;
The above custom input has the onInput and onBlur pointing to the custom hooks since i want to reuse the functionality on other input types like select and date pickers without having to duplicate them.
On my parent component am simply calling the Custom input like
function App() {
return (
<div className="container">
<CustomInput onInputHandler={} label="First name"/>
</div>
);
}
export default App;
I would like to pass the onInputHandler and value as a props back to the parent component from the custom input but am stuck on how to do this. How do i proceed?
When you say you need to pass value, I guess you wanted to pass the initial value of the input to CustomInput. To achieve that you can pass another prop.
App.js pass initialValue to CustomInput
<CustomInput
initialValue={"abc"}
label="First name"
/>
In CustomInput pass initialValue prop to useForm hook as an argument.
const { value, onInputHandler, onBlurHandler } = useForm(props.initialValue);
Set the initialValue as the value in initial state in useForm.
const useForm = (initialValue) => {
const [inputState, dispatch] = useReducer(reducer, {
...INITAL_STATE,
value: initialValue
});
...
...
}
To pass the onInputHandler as a prop you can check if onInputHandler is available as a prop and call it along with onInputHandler coming from useForm.
In App.js defines another function that accepts event as an argument.
export default function App() {
const onInputHandler = (e) => {
console.log(e);
};
return (
<div className="App">
<CustomInput
...
onInputHandler={onInputHandler}
label="First name"
/>
</div>
);
}
In CustomInput change the onInput handler like below. You can change the logic as per your needs (I called onInputHandler in useForm and prop).
<input
value={value}
onBlur={onBlurHandler}
onInput={(e) => {
props.onInputHandler && props.onInputHandler(e);
onInputHandler(e);
}}
{...props}
/>
My approach to this will be to simply call the onInputHandler() from hooks and onInputHandler() from the props received from Parent and send the e.target.value as a prop to these functions.
const CustomInput = (props) => {
const { value, onInputHandler, onBlurHandler } = useForm(); //uses custom hook
console.log(value);
const handleInputChange = (e: any) => {
onInputHandler(e);
props.onInputHandler(e.target.value);
};
return (
<>
<label htmlFor={props.id}>{props.label}</label>
<input
value={value}
onBlur={onBlurHandler}
onInput={(e) => {
handleInputChange(e);
}}
{...props}
/>
</>
);
};
export default CustomInput;
And in the parent component we can receive them as props returned from that function and use it according to our requirement.
function App() {
return (
<div className="container">
<CustomInput
label="name"
onInputHandler={(value: string) => console.log("App",value)}
/>
</div>
);
}
export default App;
sandbox link : https://codesandbox.io/s/nifty-lamport-2czb8?file=/src/App.tsx:228-339

reading value from custom element while submitting in react js

I have custom component which I am importing in my another Component as a Element tag. My custom Component consist of dropdown values. I want to read value the value of in my element tag when I submit my form
custom component :
import React, { useState, useMemo } from 'react'
import Select from 'react-select'
import countryList from 'react-select-country-list'
function CountrySelector() {
const [value, setValue] = useState('')
const options = useMemo(() => countryList().getData(), [])
const changeHandler = value => {
setValue(value)
}
return <Select options={options} value={value} onChange={changeHandler} />
}
export default CountrySelector
i want to use that custom component country selector values on my submit button:
main component:
import react from 'react';
import CountrySelector from '../../helpers/CountrySelector';
import IdType from '../../helpers/IdType';
import ProofOfAddress from '../../helpers/ProofOfAddress';
const submitForm=(e)=>{
//debugger;
e.preventDefault();
console.warn(e.target)
};
const IdentityVerification = (props) => {
const saveUser=(e)=>{
console.warn({e});
}
return (
<form onSubmit={submitForm} >
<div className='app'>
<label >Choose Issuing Country/region</label>
<CountrySelector/>
<label >Select ID Type</label>
<IdType/>
<label >Proof of Address</label>
<ProofOfAddress/>
</div>
<div className="form-actions">
<button >Submit</button>
</div>
</form>
);
};
export default IdentityVerification;
how can i read values?
The normal way to handle this would be to move the state and your changeHandler function into the parent component and pass the handler down to the child as a prop.
const IdentityVerification = (props) => {
const [value, setValue] = useState('')
const changeHandler = value => {
setValue(value)
}
return (
// ...
<CountrySelector onChange={changeHandler}/>
// ...
);
and in your child:
function CountrySelector({changeHandler}) {
// ....
return <Select options={options} value={value} onChange={changeHandler} />
}

If event is Enter Button or mouse click, do something

I have a search bar and I want the user to be able to call the handleSearch function when they click the search button or hit the enter key. The search button works fine but I can't for the life of me get it to work when the enter key is hit. Help, please :)
import React, { useState } from 'react';
import { Form, FormControl, Button } from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { searchBlogs, setSearchQuery } from '../../actions/searchBlogsAction';
function SearchComponent() {
const history = useHistory();
const dispatch = useDispatch();
const [searchInput, setSearchInput] = useState('');
const inputHandler = (e) => {
setSearchInput(e.target.value);
};
// Search blogs and redirect to the search results page
const handleSearch = (e) => {
if (e.keyCode === 13 || e == ??) {
e.preventDefault();
history.push('/search-results');
dispatch(setSearchQuery(searchInput));
dispatch(searchBlogs(searchInput));
setSearchInput('');
}
};
return (
<Form inline>
<FormControl
type="text"
size="sm"
placeholder="Search"
className="mr-sm-2"
onChange={inputHandler}
value={searchInput}
onKeyPress={handleSearch}
/>
<Button size="sm" variant="outline-secondary" onClick={handleSearch}>
Search
</Button>
</Form>
);
}
export default SearchComponent;
Try this:
<FormControl
type="text"
size="sm"
placeholder="Search"
className="mr-sm-2"
onChange={inputHandler}
value={searchInput}
onKeyPress={event => event.key === "Enter" && handleSearch()}
/>
And the handleSearch function should just be:
const handleSearch = (e) => {
e.preventDefault();
history.push('/search-results');
dispatch(setSearchQuery(searchInput));
dispatch(searchBlogs(searchInput));
setSearchInput('');
}
According to react-bootstrap docs regarding Form, you can pass onSubmit callback to the Form component, like so:
- <Form inline>
+ <Form inline onSubmit={handleSearch}>
You want to add an onSubmit event handler to the form instead.
import React, { useState } from 'react';
import { Form, FormControl, Button } from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { searchBlogs, setSearchQuery } from '../../actions/searchBlogsAction';
function SearchComponent() {
const history = useHistory();
const dispatch = useDispatch();
const [searchInput, setSearchInput] = useState('');
const inputHandler = (e) => {
setSearchInput(e.target.value);
};
// Search blogs and redirect to the search results page
const handleSearch = (e) => {
e.preventDefault();
history.push('/search-results');
dispatch(setSearchQuery(searchInput));
dispatch(searchBlogs(searchInput));
setSearchInput('');
};
return (
<Form inline onSubmit={handleSearch}>
<FormControl
type="text"
size="sm"
placeholder="Search"
className="mr-sm-2"
onChange={inputHandler}
value={searchInput}
/>
<Button type="submit" size="sm" variant="outline-secondary">
Search
</Button>
</Form>
);
}
export default SearchComponent;
Clicking the submit button in a form will trigger the submit event as will hitting the enter key.

how to get input field value on button click in react?

Could you please tell me how to get input field value on button click in react , I am using react hooks .I want to get first name and lastname value on button click. I already pass name attribute in my function component.
Here is my code
import React, { Component, useState } from 'react';
import { render } from 'react-dom';
export default function InputField({name,label}) {
const [state, setState] = useState('')
return (
<div>
<label>{label}</label>
<input type="text"
value={state}
name={name}
onChange={(e) => setState(e.target.value)} />
{state}
</div>
);
}
Use <form> tag with useRef hook
Wrap your <InputField> tags with an html <form> tag and put a react ref on the later. Like this:
import React, { Component, useRef } from 'react'
import { render } from 'react-dom'
import InputField from './inputfield'
import './style.css'
function App () {
const nameForm = useRef(null)
const handleClickEvent = () => {
const form = nameForm.current
alert(`${form['firstname'].value} ${form['lastname'].value}`)
}
return (
<div>
<form ref={nameForm}>
<InputField label={'first name'} name={'firstname'}/>
<InputField label={'last name'} name={'lastname'}/>
</form>
<button onClick={handleClickEvent}>gett value</button>
</div>
)
}
render(<App />, document.getElementById('root'))
Working example: https://stackblitz.com/edit/react-shtnxj
The Easiest Way For Me is useRef
With useRef it's pretty simple. Just add ref name and then submit.
const email = useRef(null);
function submitForm(e){
e.preventDefault();
console.log(email.current.value);
}
return (
<div>
<form onSubmit={submitForm}>
<input type="text" ref={email} />
<button>Submit</button>
</form>
</div>
)
You could always lift up the state in parent component.
codeSandbox link
Parent Component
import React from "react";
import ReactDOM from "react-dom";
import ChildComponent from "./Child";
const { useState } = React;
function App() {
const [first_name, setFirstName] = useState("");
const [last_name, setLastName] = useState("");
const handleFirstNameChange = ({ target }) => {
setFirstName(target.value);
};
const handleLastNameChange = ({ target }) => {
setLastName(target.value);
};
const handleClick = () => {
console.log(first_name);
console.log(last_name);
};
return (
<div className="App">
<ChildComponent
label="first name"
onChange={handleFirstNameChange}
value={first_name}
/>
<ChildComponent
label="last name"
onChange={handleLastNameChange}
value={last_name}
/>
<button onClick={handleClick}>Click me</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Child Component
import React from "react";
const ChildComponent = ({ label, onChange, value, name }) => {
return (
<div>
<label>{label}</label>
<input type="text" value={value} name={name} onChange={onChange} />
</div>
);
};
export default ChildComponent;
You could always combine onChange handler for first name and last name.
Hope that helps!!!
A good solution is to move the state from InputField component into index:
const [F_name, setF_name] = useState('')
const [L_name, setL_name] = useState('')
now you should pass state value and event handler to InputField to change the state when input is changed:
<InputField label={'first name'} name={'firstname'} value={F_name} changed={(name) => setF_name(name)}/>
In Your InputField field: edit it to be like:
<input type="text"
value={value}
name={name}
onChange={(e) => changed(e.target.value)} />
See Working Demo Here
import React, { useRef } from 'react'
const ViewDetail = () => {
const textFirstName = useRef(null)
const onChange = e => {
console.log(textFirstName.current.state.value)
}
return <Input maxLength={30} ref={textFirstName} placeholder="Nombre" onChange=onChange} />
}
I can think of these approaches -
You can pull the state up to the parent component.
App.js
const [user, setUser] = useState('');
return (
<Inputfield setValue={setUser} value={user} />
);
InputField.js
<input value={props.value} onChange={(e) => setValue(e.target.value)} />
You can use ref to access indiviual element value.
If you have data distributed across multiple components you can also make use of Context API
Hope this helps!
Do let me know if you need more info on any of the option. Thanks!
You should do the react hooks work on your index and pass the value and the onChange function to your InputField component.
//index page
import React, { Component, useState } from 'react';
import { render } from 'react-dom';
import InputField from './inputfield';
import './style.css';
function App() {
const [firstname, setFirstName] = useState('');
const [lastname, setLastName] = useState('');
const handleClickEvent = ()=>{
setFirstName('Will');
setLastName('smith');
}
return (
<div>
<InputField
label={'first name'}
name={'firstname'}
value={firstname}
onChange={setFirstName}
/>
<InputField
label={'last name'}
name={'lastname'}
value={lastname}
onChange={setLastName}
/>
<button
onClick={handleClickEvent}
>Get value</button>
</div>
);
}
render(<App />, document.getElementById('root'));
// input field
import React, { Component, useState } from 'react';
import { render } from 'react-dom';
export default function InputField({name,label, value, onChange}) {
return (
<div>
<label>{label}</label>
<input type="text"
value={value}
name={name}
onChange={(e) => onChange(e.target.value)} />
{value}
</div>
);
}
While keeping the majority of your structure the same, I think the simplest and most React solution is to use forwardRef() which in a nut-shell let's us communicate between then parent-component and child-components.
See working sandbox.
App.js
import React, { useRef } from "react";
import InputField from "./InputField";
import ReactDOM from "react-dom";
function App() {
const handleClickEvent = () => {
if (firstName.current && lastName.current) {
console.log(`firstName: ${firstName.current.value}`);
console.log(`lastName: ${lastName.current.value}`);
}
};
const firstName = useRef(null);
const lastName = useRef(null);
return (
<div>
<InputField ref={firstName} label={"first name"} name={"firstname"} />
<InputField ref={lastName} label={"last name"} name={"lastname"} />
<button onClick={handleClickEvent}>Get value</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
InputField.js
import React, { useState } from "react";
const InputField = React.forwardRef((props, ref) => {
const [state, setState] = useState("");
return (
<div>
<label>{props.label}</label>
<input
ref={ref}
type="text"
value={state}
name={props.name}
onChange={e => setState(e.target.value)}
/>
{state}
</div>
);
});
export default InputField;
Notice that with this structure, you are not required to pass in any state updating function as props to the InputField component. The value that you enter into each input will be strictly maintained by the individual component. It is independent from the Parent, and therefore makes it much more reusable.
The refs we created allow us to tap into specific elements of the InputField so we extract the desired values. In this case, we can get first-name and last-name through the handleClickEvent function.
you can achieve this doing the following:
import React, { Component, useState } from 'react';
import { render } from 'react-dom';
export default function InputField({name,label}) {
const [state, setState] = useState('');
const handleChange = e => {
setState(e.target.value);
};
return (
<div>
<label>{label}</label>
<input
type="text"
value={state}
name={name}
onChange={handleChange}
/>
{state}
</div>
);
}
Hopes this helps.
well one simple(but not necessarily recommended) way is to provide an id or a ref like this in index.js
<InputField label={'first name'} name={'firstname'} id={"ip1"}/>
<InputField label={'last name'} name={'lastname'} id={"ip2"}/>
and in your inputfield.js pass the id props to the input fields like this
<input type="text"
value={state}
name={name}
onChange={(e) => setState(e.target.value)}
id= {id}/>
Now you can call them in the onClick of the button like this in index.js
const handleClickEvent = ()=>{
alert(document.getElementById("ip1").value);
}
The second, more preferable way is to set the state variable in index.js
function App() {
const [stateIp1, setStateIp1] = useState('');
const [stateIp2, setStateIp2] = useState('');
const handleClickEvent = ()=>{
alert(stateIp1);
}
return (
<div>
<InputField label={'first name'} state={stateIp1} setState={setStateIp1} name={'firstname'} id={"ip1"}/>
<InputField label={'last name'}state={stateIp2} setState={setStateIp2} name={'lastname'} id={"ip2"}/>
<button
onClick={handleClickEvent}
>Get value</button>
</div>
);
}
Now your inputfield.js becomes
export default function InputField({name,label,id,setState,state}) {
return (
<div>
<label>{label}</label>
<input type="text"
value={state}
name={name}
onChange={(e) => setState(e.target.value)} id= {id}/>
</div>
);

Categories