score:11
Use
<form>
tag withuseRef
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
score:-1
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>
);
score:0
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!
score:0
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>
);
}
score:0
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.
score:0
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.
score:1
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)} />
score:1
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} />
}
score:3
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>
)
score:4
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!!!
Source: stackoverflow.com
Related Query
- how to get input field value on button click in react?
- How to set value in input field to empty by click on a button in react js?
- How to get Input value and show it on a button click in React JS
- How to add a new textfield on button click and add integer value of that input field to an array in react
- How can I get an input's value on a button click in a Stateless React Component?
- how to get current value from input field in react js
- How do I show an input field for each click on a button in react js?
- How can I get the value of an input field and use it in URL in React
- React JS user enters value in the input field on button click to display the value
- How to get input value upon button click
- get value from input on button click and enter key press react
- how to get input value on button click in stateless component?
- How to get the value of a dynamicly created input field with react
- How do I get the previous value of a field in React? I want to use it to display the user's previous input when they click 'edit' on the field
- How do i get the value of text input field using react
- How to get new value from react ace editor on button click
- How can I get the value of an input from a button click event?
- How to get the value of an input field using ReactJS?
- How to get input text value on click in ReactJS
- React - Get the value of an input by clicking on a button
- React update input value on button click
- How to get the selected value from a radio button group in React where there are multiple groups?
- React/Next.js how to get other Element event target value on button click
- How to get Input field type as props in react typescript
- How to get the time in seconds after click on submit button using React Count Down Timer
- how to add input field dynamically when user click on button in react.js
- React how to make an input field with a fixed value combined with a dynamic value
- How to reset input value after a button click that is not inside of a form in React.js
- How to get the state updated of input field of google map api in React app
- How to get the TextField value with onclick button event React Material UI
More Query from same tag
- Jest + React Testing Library: how do I mock out a method from some library that only affects one test block
- Not able to set cache-control header for my static resources Express
- Nextjs API works in local environment but not in production environment
- React js cannot change page
- Can't access a nested object attribute
- Where can we define the Theme for Material-UI in React
- react write file: nothing works (fs, file-system...)
- Reactjs how to change the state of a component from a different component
- 3rd party Javascript and CSS files in Webpack. Strange behaviour
- Why do I get TypeError when I try adding express to my first react app
- Filter function causing all elements to unmount in React
- how to extract payload from action directly in the returned object
- React, loading a script inside a form (mercadopago)
- Set MUI Select width?
- React, show quantity of how many elements match after filtering
- How import and export components (functions) in ReactJS?
- How to fetch specific array into object using javascript
- Value on Input didnt change when state change on React + Redux
- React Router mount routes from external package
- Iterating a json with nested objects and filtering depending on attributes values
- React Redux connect is not assignable to type '() => void' with typescript
- PDF is blank and damaged when downloading it from API using JavaScript and React JS
- Facebook/Google-only logins (no username/pwd) with AWS Cognito and React
- How to create React components from a JSON array?
- How to use different environment variables during React development? axios/webpack
- .velocity is not a function
- ChartJS on small screen
- Image SPFx control with Hyperlink and OnClick
- GET Request not working but POST request is working for database query
- Breadcrumb react code not working, how can i fix it?