Handle Input values when clicked React js - javascript

I was trying to handle changing of states whenever I type something inside the two text boxes and then when the user click the button, it will set the state to it's state and then console.log the current change state to the console.
Basically I have this:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
catname: '',
catamt: 0
};
this.addBudget = this.addBudget.bind(this);
}
addBudget(e) {
e.preventDefault();
this.setState({
catname: e.target.value,
catamt: e.target.value
});
console.log('console log catname here.....', this.state.catname);
console.log('console log catamt here.....', this.state.catamt);
}
}
And then inside my component where the form is sitting:
import React from 'react';
export default class AddBudget extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="cat-input">
<input
type="text"
name="categoryname"
placeholder="Budget Category"
/>
<input
type="number"
name="categoryamount"
placeholder="Target Budget"
/>
</div>
<button onClick={this.addBudget}>+</button>
);
}
}
How do I pass along my input value to my function and console log the change of state?

Something more like that, I recommended using controlled input with react.
You can read more about it here https://reactjs.org/docs/forms.html
An example for you :) https://codesandbox.io/s/2486wxkn9n
First you need to keep track on the value with the state. Second with the form you can handle the submit. This way if a user click the button or press enter you can handle the submit method.
Inside the _handleChange method you receive the event. So this is the input change. If you console.log this value you can see he have the name, the name you pass in the input. This way you can use it as a key variable for your object. So one function for 2 :).
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
catname: '',
catamt: 0
};
this.addBudget = this.addBudget.bind(this);
}
addBudget = (e) => {
e.preventDefault();
console.log('console log catname here.....', this.state.catname);
console.log('console log catamt here.....', this.state.catamt);
}
_handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return (
<AddBudget handleChange={this._handleChange} addBudget={this.addBudget} />
)
}
}
export default class AddBudget extends React.Component {
render() {
return (
<div className="cat-input">
<form onSubmit={this.props.addBudget}>
<input
type="text"
name="catname"
onChange={this.props.handleChange}
placeholder="Budget Category"
/>
<input
type="number"
name="catamt"
placeholder="Target Budget"
onChange={this.props.handleChange}
/>
<button type="submit">+</button>
</form>
</div>
);
}
}

Related

React Javascript trouble with passing user input onchange to a parent component

I'm running into a problem when passing down down a method from a parent component to a child component. The parent, FilterableProductTable has a state called filterText. FilterableProductTable renders a child component SearchBar, and passes down a function called handleChange as a prop. SearchBar calls this function onChange, so that I can transfer the user input from SearchBar to the filterText state in FilterableProductTable.
The problem I'm running into is filterText gets updated one increment too late. I logged filterText to the console and I logged the value of the user input, both in my handleChange function:
handleChange(event) {
this.setState({ filterText: event.target.value });
console.log(event.target.value + "value");
console.log(this.state.filterText + "state");
}
and the output I get in the console is:
//user input=a.
a value
state
//user input=ab
ab value
a state
//user input =a, because b was deleted(backspace key)
a value
ab state
-----As you can see the state is one increment behind the event.target.value. I'm not sure how to fix this. Below are my two functions. If someone could help me see what I'm doing wrong that would be great.
class SearchBar extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<form>
<input
type="text"
name="name"
placeholder="Search.."
onChange={this.props.handleChange}
></input>
<br />
<input type="checkbox" /> Only show items in stock
</form>
);
}
}
class FilterableProductTable extends React.Component {
constructor(props) {
super(props);
this.state = {
filterText: "",
inStockOnly: false,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ filterText: event.target.value });
console.log(event.target.value + " value");
console.log(this.state.filterText + " state");
}
render() {
console.log(this.state.filterText + " render");
return (
<div>
<SearchBar handleChange={this.handleChange} />
<ProductTable
products={this.props.products}
filterText={this.state.filterText}
inStockOnly={this.state.inStockOnly}
/>
</div>
);
}
}
That's because setting state in React is an asynchronous operation and won't be affected immediately. you need to use the setState callback for your check like this:
handleChange(event){
this.setState({filterText:event.target.value}, () => {
console.log(event.target.value+ ' value');
console.log(this.state.filterText+ ' state');
});
}

How can I keep on adding username and status instead of updating the previous one in reactJS?

I have two components. One named 'Adduser' containing form elements so that a user may add details of post. Other named 'PostAdded', in which i want to show all posts in a list item. On every click, I want 'Adduser' to grab data from input elements and pass it to 'PostAdded' in a way that 'PostAdded' show every individual post(title and post together) in a new div instead of updating previous one. What is the best approach to do it?
File 'Adduser.js'
class AddUser extends Component {
constructor(props) {
super();
this.state = {
title : "",
post : "",
}
this.handleclick = this.handleclick.bind(this);
}
handleclick() {
this.setState(prevState => ({
title : document.getElementById("title").value,
post : document.getElementById("post").value,
}));
}
render() {
return(
<div>
<input type="text" id="title" placeholder="Title here" />
<input type="text" id="post" placeholder="Post here" />
<input type="button" onClick={this.handleclick} value="Add Post" />
<PostAdded posts={this.state.post} />
</div>
)
}
}
export default AddUser;
File 'PostAdded.js'
import React, {Component} from 'react';
class PostAdded extends Component {
constructor(props) {
super();
}
render() {
return <ul>
{ this.props.posts.map(post =>
<li>{post}</li>
)}
</ul>
}
}
export default PostAdded;
In AddUser component change your state and handleclick method. I have not modified your code too much so you can understand it easily.
class AddUser extends Component {
constructor(props) {
super();
this.state = {
posts: [],
}
this.handleclick = this.handleclick.bind(this);
}
handleclick() {
// accessing values from the input
let title = document.getElementById("title").value
let post = document.getElementById("post").value
// creating a new object
let newPostObj = {title, post}
// concatenating new object to component posts state
let newPost = this.state.posts.concat(newPostObj)
// setting newPost as component new state
this.setState({
posts: newPost
})
// emptying the input fields
document.getElementById("title").value = ''
document.getElementById("post").value = ''
}
render() {
return(
<div>
<input type="text" id="title" placeholder="Title here" />
<input type="text" id="post" placeholder="Post here" />
<input type="button" onClick={this.handleclick} value="Add Post" />
<PostAdded posts={this.state.posts} />
</div>
)
}
}
In your PostAdded component update render() method
class PostAdded extends Component {
constructor(props) {
super();
}
render() {
return (
<ul>
{ this.props.posts.map((post, i) =>
<li key={`${i}-post`}><span>{post.title}</span><span>{post.post}</span></li>
)}
</ul>
)
}
}
UPDATE
Change your AddUser Component
class AddUser extends Component {
constructor(props) {
super();
this.state = {
posts: [],
title: '',
post: ''
}
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}
// called when we type something in input fields
handleChange(e) {
// you can console log here to see e.target.name and e.target.value
this.setState({
[e.target.name]: e.target.value
})
}
handleClick() {
// using spread operator to copy previous state posts and adding new post object
let newPosts = [ ...this.state.posts, { title: this.state.title, post: this.state.post}]
this.setState({
posts: newPosts,
title: '',
post: ''
})
}
render() {
return(
<div>
// added name,value attributes and onChange listener
<input type="text" name="title" value={this.state.title} onChange={this.handleChange} placeholder="Title here" />
<input type="text" name="post" value={this.state.post} onChange={this.handleChange} placeholder="Post here" />
<input type="button" onClick={this.handleClick} value="Add Post" />
<PostAdded posts={this.state.posts} />
</div>
)
}
}

Coordinated input in all text boxes

I have an exercise and I do not understand how to do it.
Build a control with 5 text boxes that the input in all text boxes is correlated. Changing input in one box changes the input in the rest of the box.
class App extends Component {
render() {
return (
<div>
<MultiInput />
</div>
);
}
}
function SameInput(props) {
return <input type="text" name="sameInput"/>
}
class MultiInput extends React.Component {
constructor(props) {
super(props);
this.state = { value: "ho" };
}
onChange = (e) => {
this.setState({ value: e.target.value });
}
render() {
return <div>
<SameInput value={this.state.value} onChange={this.onChange}></SameInput><br />
<SameInput value={this.state.value} onChange={this.onChange}></SameInput><br />
<SameInput value={this.state.value} onChange={this.onChange}></SameInput><br />
</div>
}
}
export default App;
You are passing onChange event handler function and value to SameInput functional component but you are not actually handling them in input text field in SameInput function of input element.
Try with below change it would work
function SameInput(props) {
return <input type="text" name="sameInput" onChange={props.onChange} value={props.value}/>
}

How to dynamically set State from Form input

I have 2 React parent/child components. The Child Component has a button that adds +1 to the previous state of the Parent Component, and a Form that triggers a handleChange function for the onChange event.
The Problem
From the Form input, I want to trigger a function that sets the State to the previous State, + the input in the Form.
For example, if I write 50 in input and hit submit I want the new state be 100
Here is a codesandbox: https://codesandbox.io/s/30mz2vvyo1
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 50
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState((prevState) => {
return { value: prevState.value + 1 }
});
}
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<div>
<Child value={this.state.value} handleChange={this.handleChange} handleSubmit={this.handleSubmit} />
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
<button onClick={this.props.handleChange}>Count + 1</button>
<div>{this.props.value}</div>
<form onSubmit={this.props.handleSubmit}>
<label>
Name:
<input type="text" onChange={this.props.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
The problem you are facing can be mitigated by;
You need to have two different variables in state. value, can hold your value. You also need to hold the current value of the input, let's call it inputNumber.
You need to provide an onClick function to your button. In said function, set your state in the following fashion;
Code:
this.setState({
value: this.state.value + this.state.inputNumber,
})
After doing these things, it should work as expected.
I have updated your codesandbox, you can take a look at it here.

How not to refresh the page after onClick

I have small class in react, i want to display the result on the screen after i click on the button, but before the display happens, the page reload.
how do i do it?
what am I missing?
import React, {Component} from 'react';
class InputFieldWithButton extends Component{
constructor(props){
super();
this.state = {
message: ''
};
}
handleChange(e){
this.setState({
message: e.target.value
});
}
doSomething(e){
return(
<h1>{this.state.message}</h1>
)
}
render(){
return (
<div>
<form >
<input type="text" placeholder="enter some text!" value=
{this.state.message}
onChange={this.handleChange.bind(this)}/>
<button onClick={this.doSomething.bind(this)}>Click me</button>
</form>
</div>
)
}
}
export default InputFieldWithButton;
Your button is inside a form and triggering a submit.
You can use the preventDefault() method to stop it from doing so:
doSomething(e) {
e.preventDefault();
return (
<h1>{this.state.message}</h1>
)
}
By the way, your return statement of this click handler makes no sense at the moment.
Edit
As a followup to your comment:
Can you explain me what is my mistake in the return?
Not really a mistake, but it is useless in this context as your are not doing anything with the returned object.
Where and how do you expect to use the <h1>{this.state.message}</h1> that you are returning?
If you intend to show / hide the input message in your screen you could do it with conditional rendering.
Just store a bool like showMessage in your state and render the message only if it's set to true.
Here is a small example:
class InputFieldWithButton extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
showMessage: false
};
}
handleChange = (e) => {
this.setState({
message: e.target.value
});
}
toggleMessage = (e) => {
e.preventDefault();
this.setState({ showMessage: !this.state.showMessage })
}
render() {
const { showMessage, message } = this.state;
return (
<div>
<form >
<input
type="text"
placeholder="enter some text!"
value={message}
onChange={this.handleChange}
/>
<button onClick={this.toggleMessage}>Toggle Show Message</button>
{showMessage && <div>{message}</div>}
</form>
</div>
)
}
}
ReactDOM.render(<InputFieldWithButton />, document.getElementById('root'));
<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="root"></div>
By the way, it is considered as bad practice to bind the functions inside the render method, because you are creating a new instance of a function on each render call. instead do it inside the constructor which will run only once:
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
Or you can use arrow functions which will reference this in a lexical context:
handleChange = (e) => {
this.setState({
message: e.target.value
});
}
This is what i've used in my example.
you're not specifying the buttons'type
<button type="button">
Set the type attribute on the button to be button. The default is submit since it is wrapped in a form. So your new button html should look like this:
<button type="button" onClick={this.doSomething.bind(this)}>Click me</button>

Categories