How to log data from input onto the console in React - reactjs

I would like to know how to have it where when I press enter on my keyboard, it logs whatever is in the input onto the console. Please help. Thanks!
import React, { Component } from 'react';
import './App.css';
class App extends Component {
onClick() {
alert("CLICKED");
}
onChange(eve) {
console.log(eve.target.value);
}
onSubmit() {
alert("SUBMITTED");
}
render() {
const list = ["Lebron", "Kobe", "Steph", "Kevin"];
return (
<div className="App">
<h1>{
list.map(listitem =>{
return (
<div onClick={this.onClick}>
{listitem}
</div>
)})
}</h1>
<form onSubmit={this.onSubmit}>
<input onChange={this.onChange} />
</form>
</div>
);
}}
export default App;
Please help!

Store the input value in a state variable onChange and then log it to the console onSubmit.
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
onChange = event => {
this.setState({ value: event.target.value});
}
onSubmit = event => {
const { value } = this.state;
event.preventDefault();
console.log(value);
}
render() {
const list = ["Lebron", "Kobe", "Steph", "Kevin"];
const { value } = this.state;
return (
<div className="App">
...
<form onSubmit={this.onSubmit}>
<input onChange={this.onChange} value={value}/>
</form>
</div>
);
}
}

Related

Cannot get input value on submit function

I am trying to display input value on submit. But it seems to be not working. I don't have any errors but nothing being rendered. What is wrong with the code?
import React from 'react';
import { Component } from 'react';
class App extends Component {
constructor (props) {
super(props)
this.state = {
city : ""
}
}
handleSubmit = (event)=> {
event.preventDefault();
this.setState ({
city : event.target.value
})
}
render () {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type = "text" city = "city_name" />
<button type="submit">Get Weather</button>
{this.state.city}
</form>
</div>
)
}
}
export default App;
<form
onSubmit={e=>{
e.preventDefault()
console.log(e.target[0].value)
}}>
<input type="text"/>
<button type="submit">dg</button>
</form>
that works for me very well
Remember onSubmit target:
Indicates where to display the response after submitting the form. So you can get inner elements (and their corresponding values) like normal javascript code.
const city = event.target.querySelector('input').value
handleSubmit = (event) => {
event.preventDefault();
this.setState ({ city })
}
I guess you want it to get work like below. But this is not the only way to get it done.
import React from "react";
import { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
}
handleSubmit = (event) => {
const formData = new FormData(event.currentTarget);
event.preventDefault();
let formDataJson = {};
for (let [key, value] of formData.entries()) {
formDataJson[key] = value;
}
this.setState(formDataJson);
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="city" />
<button type="submit">Get Weather</button>
{this.state.city}
</form>
</div>
);
}
}
export default App;
Code sandbox => https://codesandbox.io/s/eager-oskar-dbhhu?file=/src/App.js

Why am I getting `this.props.onAdd is not a function`?

I'm creating a simple CRUD React app that let's you manage products. Products only have a name and a price.
In my AddProduct component, my onSubmit method can successfully log this.nameInput.value, this.priceInput.value, but when I change the log to this.props.onAdd I get this.props.onAdd is not a function.
I'm following a tutorial, so I'm sure I'm missing one small thing, but could use another set of eyes on my code.
Here's my addProduct component - the onSubmit method has the this.props.onadd(...):
import React, { Component } from 'react';
class AddProduct extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
this.props.onAdd(this.nameInput.value, this.priceInput.value);
}
render() {
return (
<form onSubmit={this.onSubmit}>
<h3>Add Product</h3>
<input placeholder="Name" ref={nameInput => this.nameInput = nameInput}/>
<input placeholder="Price" ref={priceInput => this.priceInput = priceInput}/>
<button>Add</button>
<hr />
</form>
);
}
}
And here's my App.js:
import React, { Component } from 'react';
import './App.css';
import ProductItem from './ProductItem';
import AddProduct from './AddProduct';
const products = [
{
name: 'iPad',
price: 200
},
{
name: 'iPhone',
price: 500
}
];
localStorage.setItem('products', JSON.stringify(products));
class App extends Component {
constructor(props) {
super(props);
this.state = {
products: JSON.parse(localStorage.getItem('products'))
};
this.onAdd = this.onAdd.bind(this);
this.onDelete = this.onDelete.bind(this);
}
componentWillMount() {
const products = this.getProducts();
this.setState({ products });
}
getProducts() {
return this.state.products;
}
onAdd(name, price) {
const products = this.getProducts();
products.push({
name,
price
});
this.setState({ products })
}
onDelete(name) {
const products = this.getProducts();
const filteredProducts = products.filter(product => {
return product.name !== name;
});
this.setState({ products: filteredProducts });
}
render() {
return (
<div className="App">
<h1>Products Manager</h1>
<AddProduct
/>
{
this.state.products.map(product => {
return (
<ProductItem
key={product.name}
{...product}
onDelete={this.onDelete}
/>
);
})
}
</div>
);
}
}
export default App;
What's the matter with my code? When I click the Add button, I get the error.
It's because you pass no prop to the <AddProduct /> you render.
You should add it like so:
<AddProduct onAdd={this.onAdd}/>
You need to pass the props to the component:
<AddProduct onAdd={onAdd} />
Just change the following line
<form onSubmit={this.onSubmit}>
to
<form onSubmit={this.onSubmit.bind(this)}>
onAdd is a field in the props of AddProduct. It means you should delivery a function to AddProduct in App. like: <AddProduct onAdd={() => console.log('works')} />

App.js is not defined in react project

I am building a project in reactJS framework and when I had one big class App i decided to divide into a few classes. After changes I can see below error
'App' is not defined
Can anybody help me with this problem?
I tried all webpack settings but it doesn't help. It appears only after dividing the class 'App' but, before it was working fine.
Here is my code.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
list,
searchTerm: "",
};
this.onDismiss = this.onDismiss.bind(this);
this.onSearchChange = this.onSearchChange.bind(this);
}
onSearchChange(event){
this.setState({ searchTerm: event.target.value });
}
onDismiss(id) {
const isNotId = item => item.objectID !== id;
const updatedList = this.state.list.filter(isNotId);
this.setState({ list: updatedList });
}
render() {
const { searchTerm, list } = this.state;
return (
<div className="App">
<Search
value = {searchTerm}
onChange = {this.onSearchChange}
/>
<Table
list = {list}
pattern = {searchTerm}
onDismiss = {this.onDismiss}
/>
</div>
);
}
}
class Search extends Component {
render(){
const { value, onChange } = this.props;
return(
<form>
<input
type = "text"
value = "value"
onChange = {onChange}
/>
</form>
);
}
}
class Table extends Component {
render(){
const { list, pattern, onDismiss } = this.props;
return(
<div>
{list.filter(isSearched(pattern)).map(item =>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
<span>
<button onClick={() => onDismiss(item.objectID)} type="button">
Delete
</button>
</span>
</div>
)}
</div>
);
}
};
}
export default App;
The answer you'll need is here
Few things I would like to explain. Check my comments in the code below
import React, { Component } from 'react';
import './App.css'; // have proper naming conventions change it to lowercase app.css
export default class App extends Component {
constructor(props){
super(props);
this.state = {
list,
searchTerm: "",
};
//Manual binding are ok but if you use arrow function you can stay away with scope related issues like let that = this;
//this.onDismiss = this.onDismiss.bind(this);
//this.onSearchChange = this.onSearchChange.bind(this);
}
onSearchChange = (event) => {
this.setState({ searchTerm: event.target.value });
}
onDismiss = (id) => {
const isNotId = item => item.objectID !== id;
const updatedList = this.state.list.filter(isNotId);
this.setState({ list: updatedList });
}
render() {
const { searchTerm, list } = this.state;
return (
<div className="App"> //Follow naming conventions chang classname App to app
<Search
value = {searchTerm}
onChange = {this.onSearchChange}
/>
<Table
list = {list}
pattern = {searchTerm}
onDismiss = {this.onDismiss}
/>
</div>
);
}
}
//you need to export your component to make it available to other components
export class Search extends Component {
render(){
const { value, onChange } = this.props;
return(
<form>
<input
type = "text"
value = "value"
onChange = {onChange}
/>
</form>
);
}
}
//you need to export your component to make it available to other components
export class Table extends Component {
render(){
const { list, pattern, onDismiss } = this.props;
return(
<div>
{list.filter(isSearched(pattern)).map(item =>
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
<span>
<button onClick={() => onDismiss(item.objectID)} type="button">
Delete
</button>
</span>
</div>
)}
</div>
);
}
};
}

How to toggle attributes of elements created on child components that were generated after a form submission

I have the following code where someone can add names into a an array of objects. I can't get to toggle one of the elements created after submission.
import React, { Component } from 'react';
import User from './User';
class App extends Component {
constructor(props){
super(props);
this.state = {
list:list,
searchTerm:'',
userInputValue:'',
users:[],
};
}
userUpdateMethod = e =>
this.setState({
userInputValue:e.target.value
});
newUserSubmitHandler = (e) =>{
e.preventDefault();
this.setState({
users: this.state.users.concat([{name:this.state.userInputValue,isConfirmed:false}]),
userInputValue:""
});
}
toggleAttendance = () =>{
const toggleConfirmed = this.state.users.isConfirmed;
this.setState({
users:!toggleConfirmed
});
}
render() {
const {searchTerm, list} =this.state;
return (
<div className="App">
<User
a = {this.state.userInputValue}
b = {this.userUpdateMethod}
c = {this.newUserSubmitHandler}
d = {this.state.users}
e = {this.toggleAttendance}
/>
</div>
);
}
}
export default App;
The function that I can get to work is toggleAttendance and it resides on the User component
import React, { Component } from 'react';
const User = props =>
<div>
<h2>User Component</h2>
<form onSubmit={props.c}>
<input type="text" onChange={props.b} value = {props.a}/>
<button type="submit" name="submit" value="submit"> Submit</button>
</form>
<div>The follwowing will be attending:{props.d.map((user,index) =>
<div> {user.name} is {user.isConfirmed? "coming":"not coming"}
<button onClick={()=>props.e(index)}>toggle attendance</button>
</div>
)}
</div>
</div>;
export default User;
I have tried several ways to update the toggleAttendance method from the main App component but with no luck

Creating onClick event for datalist option in React

I've made a Twitch API widget which you can see here: https://twitch-react-drhectapus.herokuapp.com/
At the moment, any time you search for something, there will be a list of suggestions. I'd like to make it so that when you click on one of the datalist options it will search for that user, rather than having to click on the 'Search' button. Basically the same search function as google has.
How do I go about implementing this?
Code:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser, fetchSuggestions } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
term: ''
};
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
this.setState({
term: event.target.value
});
setTimeout( this.props.fetchSuggestions(event.target.value), 300);
}
renderSuggestions(sug, i) {
return (
<option key={i} value={sug.display_name} />
)
}
onFormSubmit(event) {
event.preventDefault();
this.props.fetchUser(this.state.term);
this.setState({
term: ''
});
}
render() {
const { error, suggestions } = this.props;
return (
<form
className='input-group'
onSubmit={this.onFormSubmit}>
<input
className='form-control'
placeholder='Search for a Twitch user'
value={this.state.term}
onChange={this.onInputChange}
list='suggestions' />
<span className='input-group-btn'>
<button className='btn btn-primary'>
Search
</button>
</span>
<datalist id='suggestions'>
{suggestions.map(this.renderSuggestions)}
</datalist>
</form>
// {/* {error && <div className='alert alert-danger'>{error}</div>} */}
)
}
}
function mapStateToProps({ error, suggestions }) {
return { error, suggestions };
}
export default connect(mapStateToProps, { fetchUser, fetchSuggestions })(SearchBar);

Resources