Passing react text field input values as parameters to a method - javascript

I have the below input fields of which I need to get the entered inputs and pass it to the onClick event of the button shown below.
<input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/>
<input type="text" style = {textFieldStyle} name="payloadBox" placeholder="Enter payload here..."/>
<button value="Send" style={ buttonStyle } onClick={this.publish.bind(this,<value of input field 1>,<value of input field2>)}>Publish</button><span/>
I have a method called publish which takes two string arguments. In place of those strings, I need to pass the values entered in the input fields. How can I achieve this without storing the values in states? I do not want to store the input field values in state variables. Any help would be much appreciated.

How can I achieve this without storing the values in states?
I think in this case better use states
class App extends React.Component {
constructor() {
super();
this.state = {
topicBox: null,
payloadBox: null
};
this.publish = this.publish.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
this.setState({
[target.name]: target.value
});
}
publish() {
console.log( this.state.topicBox, this.state.payloadBox );
}
render() {
return <div>
<input
type="text"
name="topicBox"
placeholder="Enter topic here..."
value={ this.state.topicBox }
onChange={ this.handleChange }
/>
<input
type="text"
name="payloadBox"
placeholder="Enter payload here..."
value={ this.state.payloadBox }
onChange={ this.handleChange }
/>
<button value="Send" onClick={ this.publish }>Publish</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

You can add ref for each text field, and read the value from it like:
class App extends React.Component {
constructor() {
super();
this.publish = this.publish.bind(this);
}
publish(topicBox, payloadBox) {
alert(this.refs.topic.value);
alert(this.refs.payload.value);
}
render() {
return <div>
<input
ref="topic"
type="text"
name="topicBox"
placeholder="Enter topic here..."/>
<input
ref="payload"
type="text"
name="payloadBox"
placeholder="Enter payload here..."/>
<button
value="Send"
onClick={this.publish}>
Publish
</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
Working fiddle https://jsfiddle.net/hjx3ug8a/15/
Thanks for Alexander T for his addition!

Related

How do I calculate the contents of the input bar? - ReactJS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So I have a formula I want to apply to the calculate button so when clicked it runs the input number through my function and displays the result of it.
I have the input bar and the button, but what do I need to make the button respond to the content in the input bar?
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<form>
<label>
Total
<input type="text" name="name" />
</label>
<input type="submit" value="Calculate" />
</form>
</header>
</div>
);
}
export default App;
First of all, for any input, make a state.
Then, you can use the onSubmit attribute on the <form> element to call your method.
To display input, you just simply use the state.
For examples, you can find them at the official docs, https://reactjs.org/docs/forms.html
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} /> </label>
<input type="submit" value="Submit" />
</form>
);
}
}
Functional Component
function NameForm(props) {
const [value, setValue] = useState("");
const handleChange = (e) => setValue(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
console.log("Form was submitted with input " + value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={value} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
)
}

useState not working with render in React app

I am a beginner in React and trying to make a CRUD app. I have this code snipped where useState is being used but when I use the same in a class with render function it gives an error. Can someone explain me why and can convert this code to suit a class with render
export default function App(){
const[userName,setUserName]=useState('');
const[password,setPassword]=useState('');
return(
<div className="CreatePost">
<label>UserName</label>
<input type="text"
onChange={(e)=>{
setUserName(e.target.value);
}}
/>
<label>Password</label>
<input type="text"
onChange={(e)=>{
setPassword(e.target.value);
}}
/>
</div>
);
}
useState() only works in functional component. if you want to modify state in a class based component you have to do it with setState method. Something like this should work
export default class App extends React.Component{
constructor() {
this.state ={ userName : "" , password: "" }
}
render() {
return(
<div className="CreatePost">
<label>UserName</label>
<input type="text"
onChange={(e)=>{
this.setState( {userName : e.target.value} );
}}
/>
<label>Password</label>
<input type="text"
onChange={(e)=>{
this.setState( {password : e.target.value} );
}}
/>
</div>
);
}
}
You cannot use hook inside class component. Convert your existing component into the class based as following:
class App extends React.PureComponent {
state = {
userName: '',
password: '',
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
}
render () {
const { userName, password } = this.state;
return (
<div className="CreatePost">
<label>UserName</label>
<input type="text" value={userName} onChange={this.handleChange}/>
<label>Password</label>
<input type="text" value={password} onChange={this.handleChange}/>
</div>
)
}
}

How to use onchange on 2 input fields in React

I am trying to catch 2 input field's value but none of the input fields is working.
when I comment second Input field than the first one works properly.
state = { zipcode: null, city: "" };
onFormSubmit = event => {
event.preventDefault();
//Callback
this.props.onEnter(this.state.zipcode);
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="number"
className={`form-control`}
placeholder="Enter ZIP code"
name="zipcode"
onChange={this.handleChange} />
<input
type="text"
className={`form-control`}
placeholder="Enter Zip-code"
name="city"
onChange={this.handleChange}/>
</form>
</div>
);
}
}
When I hit enter after entering a query in the first input field I get no output and no error.
I tried below code and it worked just fine. Maybe there is something wrong with your callback function. Because on form submission you are getting the correct values.
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
zipcode: null,
city: ""
}
}
onFormSubmit = event => {
event.preventDefault();
//Callback
console.log(this.state);
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="number"
className={`form-control`}
placeholder="Enter ZIP code"
name="zipcode"
onChange={this.handleChange} />
<input
type="text"
className={`form-control`}
placeholder="Enter Zip-code"
name="city"
onChange={this.handleChange}/>
<input type="submit" value="submit" />
</form>
</div>
);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
Here is the jsfiddle link with your code. Check in the inspect element after clicking on the submit button.
It works.
https://jsfiddle.net/t4o0xawr/1/

Addition of two numbers in reactjs

I have two input boxes to take user input as numbers and want to display their addtion as a result in span but they are not added they are appended.
This is my reactjs that i have tried:
class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value:'',
fno:'',
sno:'',
};
this.handleSquareChange = this.handleSquareChange.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
this.handleTextLastChange = this.handleTextLastChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSquareChange(event) {
this.setState({value: event.target.value});
}
handleTextChange(event) {
this.setState({fno: event.target.value});
}
handleTextLastChange(event) {
this.setState({sno: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
alert("welcome");
}
render() {
return (
<div className="example">
<form onSubmit={this.handleSubmit}>
<span>Square of:</span>
<input type="text" value={this.state.value} onChange=
{this.handleSquareChange} />
<span>First no:</span>
<input type="text" value={this.state.fno} onChange=
{this.handleTextChange} />
<span>second no:</span>
<input type="text" value={this.state.sno} onChange=
{this.handleTextLastChange} />
<input type="submit" value="Submit" onClick={this.handleSubmit} />
</form>
<div className="preview">
<h1>Square of no is</h1>
<div>{this.state.value * this.state.value}</div>
</div>
<div className="preview">
<h1>Result of no is</h1>
<div>{this.state.fno + this.state.sno}</div>
</div>
</div>
);
}
}
ReactDOM.render(<EssayForm />, document.getElementById('app'));
I have taken a input box to square a number it works fine but not addition.Anybody can let me know where i am wrong.I am new to reactjs.
In your state you have defined sno and fno as string. Therefore when you set anything to them they make the value as string. What you can do is make sno and fno filed as number by giving them the default value of 0. Or, you can typecast them to number before adding. Like, (Number)this.state.fno + (Number)this.state.sno.
handleTextChange(event) {
this.setState({fno: Number(event.target.value)});
}
handleTextLastChange(event) {
this.setState({sno: Number(event.target.value)});
}
just replace the functions.Hope this will solve your problem
This is code for you;
class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value:'',
fno:'',
sno:'',
};
this.handleChange = this.handleChange(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
}
handleSubmit(event) {
event.preventDefault();
alert("welcome");
}
render() {
const { fno, sno, value } = this.state;
return (
<div className="example">
<form onSubmit={this.handleSubmit}>
<span>Square of:</span>
<input
type="text"
name="value"
value={value}
onChange={this.handleChange}
/>
<span>First no:</span>
<input
name="fno"
type="text"
value={fno}
onChange={this.handleChange}
/>
<span>second no:</span>
<input
type="text"
name="sno"
value={sno}
onChange={this.handleChange}
/>
<input type="submit" value="Submit" onClick={this.handleSubmit} />
</form>
<div className="preview">
<h1>Square of no is</h1>
<div>{Number(value) * Number(value)}</div>
</div>
<div className="preview">
<h1>Result of no is</h1>
<div>{Number(fno) + Number(sno)}</div>
</div>
</div>
);
}
}
ReactDOM.render(<EssayForm />, document.getElementById('app'));

How to get form data from input fields in React

The constructor and function:
constructor(props) {
super(props);
this.state = {
tagline: 'We rank what people are talking about.',
year: new Date().getFullYear()
};
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
console.log('onFormSubmit', e)
console.log('this.state', this.state);
};
The form (classNames removed for clarity):
<form onSubmit={ this.onFormSubmit }>
<div className="fl w100">
<div>
<input type="text" id="email" value={ this.state.email }/>
<label htmlFor="email">Email</label>
</div>
</div>
<div className="fl w100">
<div>
<input type="password" id="password" value={ this.state.password }/>
<label htmlFor="password">Password</label>
</div>
</div>
<button type="submit">
Login
</button>
</form>
This is what logs out, note no email or password information:
Full Login component code
import React from 'react';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
tagline: 'We rank what people are talking about.',
year: new Date().getFullYear()
};
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
console.log('onFormSubmit', e)
console.log('this.state', this.state);
};
render() {
return (<div className="app">
<div className="welcome">
<header>
<div className="wikitags-logo">
<img src="imgs/wikitags-logo.png"/>
</div>
<h2>Admin Portal</h2>
<p>{ this.state.tagline }</p>
</header>
<section className="login-form">
<form onSubmit={ this.onFormSubmit }>
<div className="fl w100">
<div className="mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" type="text" id="email" value={ this.state.email }/>
<label className="mdl-textfield__label" htmlFor="email">Email</label>
</div>
</div>
<div className="fl w100">
<div className="mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" type="password" id="password" value={ this.state.password }/>
<label className="mdl-textfield__label" htmlFor="password">Password</label>
</div>
</div>
<button type="submit" className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
Login
</button>
</form>
</section>
<footer>
© { this.state.year } WikiTags
</footer>
</div>
</div>);
}
}
export default Login;
Suggestions:
1. You are using value property with input fields but you didn't defined the onChange method so your input fields will be read-only because state value will not get updated.
2. You need to define a onChange event will all the input fields or make them uncontrolled element by removing the value property.
3. In case of uncontrolled element define the ref to each field and to access the value use this.ref_name.value.
By Defining the onChange event:
Define the name property to each input element (name should be same as state variable name it will help to update the state and we can handle all the change in single onChange function) like this:
<input type="text" name='value' value={this.state.value} onChange={(e) => this.handleChange(e)} />
handleChange(e){
this.setState({[e.target.name]: e.target.value})
}
By Uncotrolled element:
<input type="text" ref={el => this.el = el} />
Now inside onSubmit function use this.el.value to access he values of this input field.
Check this answer for reference: https://stackoverflow.com/a/43695213/5185595
You are not getting email or password information because you're passing in the state console.log('this.state', this.state); and you haven't set a state for the email and password.
Now, you got two options:
Set the state and get the form info from there
Pass the input value to a function that handles the info
For option 1, you'll need to set a state for your email and password (although setting a state for a password is not recommended) and an onChange event handler on the input(s).
Set up your onChange event handlers.
<form onSubmit={ this.onFormSubmit }>
<input type="text" id="email" onChange={this.handleEmailChange} value={ this.state.email } />
<input type="password" id="password" onChange={this.handlePasswordChange} value={ this.state.password } />
<button type="submit">
Login
</button>
</form>
And the functions to set the email and password states.
handleEmailChange(event) {
this.setState({ email: event.target.value });
}
handlePasswordChange(event) {
this.setState({ password: event.target.value });
}
And don't forget to initialize the state for your email and password in the constructor and bind the functions.
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
And you're done! Then on the onFormSubmit function just access the email and password values from the state this.state.email and this.state.password and do whatever you like.
Now for option 2, you can just pass in the event.target.value of the inputs, those are the values for the email and the password, and pass those values to a form event handler onSubmit function, from there you can do whatever you want (set the state or update the email and password, change them, whatever).
<form onSubmit={ this.onFormSubmit }>
<input type="text" id="email" name="theEmail" />
<input type="password" id="password" name="thePassword" />
<button type="submit">
Login
</button>
</form>
And the onFormSubmit function.
onFormSubmit(event) {
const email = event.target.theEmail.value;
const password = event.target.thePassword.value;
// do stuff
console.log('Email:', email);
console.log('Password:', password);
};
The easier and recommended way to accomplish what you're trying to do is the option 2.
Remember, the less state your app handles the better.
So how I would approach this is to store the values in your state using what is called a controlled component. Making a controlled component is very simple, this is a basic implementation:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
The key here is the handleChange function, and the onChange attribute. Every time the input field changes, the handleChange function is going to be called and the state will be updated.
You can find more info form the documentation here: https://facebook.github.io/react/docs/forms.html

Categories

Resources