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

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>
)
}

Related

How to call a function in a function based ReactJS component?

In ReactJS would like to have a component from a function, and send a call to a function when a form is posted.
This example doesn't work. How can be fixed?
import React from 'react';
import Link from "react-router-dom/Link";
function AddPhoto(props) {
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
<form className="form" onSubmit={e => this.handleSubmit(e)}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
export function handleSubmit(event) {
console.log("Form has been submitted");
console.log(event.target.element.link.value);
}
I think there are several issues with your code.
You probably want to export your AddPhoto component instead of your handleSubmit function. Assuming that your file is only exporting your AddPhoto component, you don't have to declare a constant and you can straightaway export default your AddPhoto function.
I actually don't see the reason to export your handleSubmit function. So I will include that function inside your AddPhoto component.
There is a - in your this.handleSubmit function, also functional component don't have to use this, furthermore your handleSubmit function is not within your functional component's scope. So it won't work.
You probably don't need the . in your input className props as well.
I've formatted your code to make it look cleaner :)
Here are the codes for you to refer.
const AddPhoto = (props) => {
const handleSubmit = (event) => {
// Add this if you want to prevent the page from reloading and updating your url
event.preventDefault();
console.log("Form has been submitted");
// Assuming you want to get the `link` field's value, you can get it by using this
console.log(event.target.link.value);
}
return (
<div>
<h1>Pickture</h1>
<Link className="cancelIcon" to="/">
{" "}
</Link>
<div>
<form className="form" onSubmit={handleSubmit}>
<input
className="form input"
type="text"
placeholder="Link"
name="link"
/>
<input
className="form input"
type="text"
placeholder="Description"
name="description"
/>
<button type="submit">post</button>
</form>
</div>
</div>
);
}
export default AddPhoto;
Remove this from your handleSubmit since it's declared outside.
Remove export if you're declaring the function in the same file. Otherwise, you would have to define your function in a separate file and then import from there.
function AddPhoto(props) {
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
{/* Removed this.*/}
<form className="form" onSubmit={e => handleSubmit(e)}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
// Removed export
function handleSubmit(event) {
console.log("Form has been submitted");
console.log(event.target.element.link.value);
}
There are quite some issue with your code:
The button doesn’t have a type=“submit” on it, so therefor it won’t even submit the form when pressed.
HandleSubmit is an function specific to AddPhoto, so it should be inside the AddPhoto component. (I also like to use an arrow function in this case because it should be an anonymous function).
There is no need the use this because first of all this keyword is only used in classes to bind functions to the class. So because AddPhoto is an functional component, you don’t have to bind the function to the class.
You should add event.preventDefault();, because otherwise the page will reload (to submit the form) and you will lose your state of your application.
import React from 'react';
import Link from 'react-router-dom/Link';
export default function AddPhoto() {
const handleSubmit = event => {
event.preventDefault();
const link = event.target.link;
const description = event.target.description;
console.log('Form has been submitted');
};
return (
<div>
<h1>Picture</h1>
<Link className="cancelIcon" to="/">
cancel
</Link>
<div>
<form className="form" onSubmit={handleSubmit}>
<input
className="form-input"
type="text"
placeholder="Link"
name="link"
ref={linkInput}
/>
<input
className="form-input"
type="text"
placeholder="Description"
name="description"
ref={descriptionInput}
/>
<button type="submit">post</button>
</form>
</div>
</div>
);
}
Try this:
import React from 'react';
import Link from "react-router-dom/Link";
export function AddPhoto(props) {
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
<form className="form" onSubmit={handleSubmit}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
function handleSubmit(event) {
console.log("Form has been submitted");
console.log(event.target.element.link.value);
}
I think you should be needing to write something like ...
import React from 'react';
import Link from "react-router-dom/Link";
export const AddPhoto = props => {
const handleSubmit = e =>{
return(
console.log("Form has been submitted");
console.log(e.target.element.link.value);
)
}
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
<form className="form" onSubmit={e => handleSubmit(e)}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
AddPhoto.defaultProps = {
onSubmit: ()=>{}
}

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'));

Text input unfocused after one character React?

var uuid = require('uuid-v4');
// Generate a new UUID
var myUUID = uuid();
// Validate a UUID as proper V4 format
uuid.isUUID(myUUID); // true
var questionNum = 0;
class App extends Component {
constructor(props){
super(props);
this.state = {
key: uuid(),
title: "",
author: "",
questions: [],
answers: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
addQuestion = () => {
questionNum++;
this.setState({
questions: this.state.questions.concat(["question","hi"])
});
console.log(this.state.questions);
this.setState({
answers: this.state.answers.concat(["hello","hi"])
});
console.log(this.state.answers);
console.log(questionNum);
console.log(this.state.title);
console.log(this.state.author);
}
render() {
return (
<div className="App">
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Quiz Form 2.0</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
<div>
<form>
<div className="Intro">
Give your Quiz a title: <input type="text" value={this.state.title} onChange={this.handleChange} name="title" key={uuid()}/><br/>
Who's the Author? <input type="text" value={this.state.author} onChange={this.handleChange} name="author" key={uuid()}/><br/><br/>
</div>
<div className="questions">
Now let's add some questions... <br/>
{this.addQuestion}
</div>
</form>
<button onClick={this.addQuestion}>Add Question</button>
</div>
</div>
);
}
}
export default App;
Both of the inputs on my page unfocus after typing only one character. Here's my code, I'm not entirely sure where I am going wrong here, it all worked just fine yesterday.
If there is anything else that you need to know just leave a comment and I will get to it. Your help is much appreciated, thanks!
When the key given to a component is changed, the previous one is thrown away and a new component is mounted. You are creating a new key with uuid() every render, so each render a new input component is created.
Remove the key from your inputs and it will work as expected.
<div className="Intro">
Give your Quiz a title:
<input
type="text"
value={this.state.title}
onChange={this.handleChange}
name="title"
/>
<br/>
Who's the Author?
<input
type="text"
value={this.state.author}
onChange={this.handleChange}
name="author"
/>
<br/><br/>
</div>
Tholle's response is correct. However, you should make some adjustments to how you interact with state. I've reworked your code with comments and included the uuid fix.
class App extends Component {
constructor(props){
super(props);
this.state = {
title: "",
author: "",
questions: [],
answers: []
}
this.handleChange = this.handleChange.bind(this);
this.addQuestion = this.addQuestion.bind(this);
}
handleChange({ target }) {
// since you'll always have a synthetic event just destructure the target
const { checked, name, type, value } = target;
const val = type === 'checkbox' ? checked : value;
this.setState({
[name]: val
});
}
addQuestion() {
// never modify state directly -> copy state and modify
const { answers, questions } = Object.assign({}, this.state);
// update your answers
answers.push(["hello", "hi"]);
// update your questions
questions.push(["question", "hi"]);
// now update state
this.setState({
answers,
questions
}, () => {
console.log(this.state);
});
}
render() {
return (
<div className="App">
<div>
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Quiz Form 2.0</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
<div>
<form>
<div className="Intro">
Give your Quiz a title: <input type="text" value={this.state.title} onChange={this.handleChange} name="title" /><br/>
Who's the Author? <input type="text" value={this.state.author} onChange={this.handleChange} name="author" /><br/><br/>
</div>
<div className="questions">
Now let's add some questions... <br/>
{this.addQuestion}
</div>
</form>
<button onClick={this.addQuestion}>Add Question</button>
</div>
</div>
);
}
}
export default 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

Passing react text field input values as parameters to a method

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!

Categories

Resources