error:cannot read property "props " of undefined - reactjs

I am having a troubling error "cannot read property "props" of undefined" in reactjs sorry for noob questions can anyone help me with this??
app component
export default class App extends Component {
constructor(props){
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(){
console.log("something");
}
render() {
return (
<div>
<Form onSubmit={this.onSubmit}></Form>
</div>
)
}
}
form component
export default function Form() {
const {onSubmit} = this.props;
return (
<div className="form">
<input className="textbar" placeholder="Search for username" name="name"></input>
<button className="button" onClick={()=>onSubmit} >Search</button>
</div>
)
}
the error is in form component in 2nd line.

You should define props as the argument of the function, as such:
export default function Form(props) {
const {onSubmit} = props;
return (
<div className="form">
<input className="textbar" placeholder="Search for username" name="name"></input>
<button className="button" onClick={()=>onSubmit} >Search</button>
</div>
)
}
Then you can simply destructure props by:
const {onSubmit} = props;

Form is a functional component, you can not use this there.
change Form to this:
export default function Form({onSubmit}) {
return (
<div className="form">
<input className="textbar" placeholder="Search for username" name="name"></input>
<button className="button" onClick={onSubmit} >Search</button>
</div>
)
}

Related

My onchange method is not working in react

import React, { Component } from 'react';
import TaskBar from './Task';
class Todo extends Component {
state = {
todo: ''
}
changeHandler = (event) => {
console.log(event.target.value);
}
render() {
return (
<React.Fragment>
<div className="card">
<h5 className="card-header">Todo</h5>
<div className="card-body">
<h5 className="card-title">Task you want to do</h5>
<form>
<input type="text" className="form-control" value={this.state.todo} name="todo" onChange={(event) => this.changeHandler(event)} />
</form>
</div>
<button className="btn btn-primary">Go somewhere</button>
</div>
</React.Fragment>
)
}
}
export default Todo;
In the above code i don't know why i couldn't make any change
2) I am using Bootstrap cdn in my public folder and i am using these classes here
You forgot to set state inside your onchange handler.
import React, { Component } from 'react';
import TaskBar from './Task';
class Todo extends Component {
state = {
todo: ''
}
changeHandler = (event) => {
console.log(event.target.value);
this.setState({todo: event.target.value}) //you forgot to do this//
}
render() {
return (
<React.Fragment>
<div className="card">
<h5 className="card-header">Todo</h5>
<div className="card-body">
<h5 className="card-title">Task you want to do</h5>
<form>
<input type="text" className="form-control" value={this.state.todo} name="todo" onChange={(event) => this.changeHandler(event)} />
</form>
</div>
<button className="btn btn-primary">Go somewhere</button>
</div>
</React.Fragment>
)
}
}
export default Todo;
Link to a codesandbox example - https://codesandbox.io/s/jydjj?module=/example.js
Also currently your onchange uses an arrow function which creates a new function on every hit which is considered bad practice so i would suggest you to do this instead.
<input type="text" className="form-control" value={this.state.todo} name="todo" onChange={this.changeHandler} />

Set state not setting the state

I have a very simple component with a single state, I initialize the state when component is created and try to change it when a form is submitted.
It doesn't work for some reason.
import React, { Component } from "react";
export default class AddTodo extends Component {
constructor() {
super();
this.state = {
submited: false
};
}
handleSubmit = event => {
this.setState = {
submited: true
};
alert("Submited state: " + this.state.submited);
event.preventDefault();
};
render() {
return (
<div className="container mt-3">
<form onSubmit={this.handleSubmit}>
<div className="input-group mb-3">
<input
type="text"
className="form-control"
placeholder="New Todo Description Here"
/>
<div className="input-group-append">
<button className="btn btn-primary" type="submit">
Add Todo
</button>
</div>
</div>
</form>
</div>
);
}
}
this.setState is a function, so call it like one using brackets ().
this.setState({
submited: true
});
import React, { Component } from "react";
export default class AddTodo extends Component {
constructor() {
super();
this.state = {
submited: false
};
}
handleSubmit = event => {
this.setState({
submited: true
},()=>{
alert("Submited state: " + this.state.submited);
event.preventDefault();
});
};
render() {
return (
<div className="container mt-3">
<form onSubmit={this.handleSubmit}>
<div className="input-group mb-3">
<input
type="text"
className="form-control"
placeholder="New Todo Description Here"
/>
<div className="input-group-append">
<button className="btn btn-primary" type="submit">
Add Todo
</button>
</div>
</div>
</form>
</div>
);
}
}
As you can see here setState is a function, but you're assigning a value to it.
The problem is here:
this.setState = {
submited: true
};
It should be:
this.setState({submitted: true}); // Mind the typo also
Just to make a quick note, the React team published react hooks in version 16.8 as a replacement to class components that have some drawbacks. I would give it a try, the docs are here.
With hooks your code would look like this:
import React, { useState } from 'react';
function AddTodo() {
// Declare a new state variable, which we'll call "count"
const [isSubmitted, setSubmission] = useState(false);
function handleSubmit(event) {
setSubmission(true);
event.preventDefault();
}
return (
<div className="container mt-3">
<form onSubmit={handleSubmit}>
<div className="input-group mb-3">
<input
type="text"
className="form-control"
placeholder="New Todo Description Here"
/>
<div className="input-group-append">
<button className="btn btn-primary" type="submit">
Add Todo
</button>
</div>
</div>
</form>
);
}

Getting undefined for Field name in reduxform

I have redux form in a class component and for some reason when I console log the formValues I am getting undefined what is the problem?
class CreateTeamBox extends Component{
handleFormSubmit({name}){
console.log(name);
}
renderError = ({ touched, error}) => {
if(touched && error) {
return(
<div>{error}</div>
);
}
}
renderInput = ({input, label, type, meta}) => {
return(
<div className={styles.formGroup}>
<label>{label}</label>
<input {...input} />
<div className={styles.errorWrapper}>
{this.renderError(meta)}
</div>
</div>
);
}
render() {
const {handleSubmit, error} = this.props ;
return(
<div className={styles.createTeamBox}>
<div className={styles.titleWrapper}>
<h2>create team</h2>
</div>
<div className={styles.bodyWrapper}>
<div className={styles.submitErrorWrapper}>
{error ? <Error error={error} /> : null}
</div>
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<Field name="name" component={this.renderInput} label="name" />
<button className={styles.button} type="submit" >create</button>
</form>
</div>
</div>
)
}
}
const validate = (formValues) => {
console.log(formValues.name);
const name = formValues.name;
const errors = validateForm(name);
return errors;
}
export default reduxForm({
form: 'createTeamForm',
validate
})(CreateTeamBox);
I have other reduxform in the same given project with different names, is it causing the problem? Im not sure why it is happening as I havecopied most of the coe from working reduxform in the given project .
the default value of formValues will be empty object, after enter some data to the field then you can get the value, or you can pass the value by using initialValues

How to accept and pass two parameter as props

Hi I need to pass two parameters, to the class Chat. Currently it is getting only one parameter and displaying correctly.
const Chat = props => (
<div >
<ul>{props.messages.map(message => <li key={message}>{message}</li>)}</ul>
</div>
);
This Chat.js file is called from the Home.js. Suppose I need to pass the Chat component two parameters and I tried it like following.
import React, { Component } from 'react';
import { User } from './User';
import Chat from './Chat';
export class Home extends Component {
displayName = Home.name
state = {
messages: [],
names: []
};
handleSubmit = (message,name) =>
this.setState(currentState => ({
messages: [...currentState.messages, message],
names: [...currentState.names,name]
}));
render() {
return (
<div>
<div>
<User onSubmit={this.handleSubmit} />
</div>
<div>
<Chat messages={this.state.messages,this.state.name} />
</div>
</div>
);
}
}
In this scenario how should I change the Chat component to accept two parameters and display inside div tags.
This is what I tried. But seems it is incorrect.
const Chat = props => (
<div >
<ul>{props.messages.map((message, name) => <li key={message}>{message}</li> <li key={name}>{name}</li>)}</ul>
</div>
);
PS: The User Method
import * as React from 'react';
export class User extends React.Component{
constructor(props) {
super(props);
this.state = {
name: '',
message: ''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div className="panel panel-default" id="frame1" onSubmit={this.handleSubmit}>
<form className="form-horizontal" action="/action_page.php" >
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="name">Your Name </label>
<div className="col-sm-10">
<input type="text" className="form-control" name="name" placeholder="Enter your Name" onChange={this.handleChange} />
</div>
</div>
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="message">Message</label>
<div className="col-sm-10">
<input type="text" className="form-control" name="message" placeholder="Enter your Message" onChange={this.handleChange}/>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit" id="submit" className="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
);
}
handleChange(evt) {
this.setState({ [evt.target.name]: evt.target.value });
}
handleSubmit = (e) => {
e.preventDefault();
this.props.onSubmit(this.state.message, this.state.name);
this.setState({ message: "" });
this.setState({name:""});
};
}
You can do this by using separate attributes to pass different props. So for instance, you might revise your <Home/> components render method like so:
<Chat messages={this.state.messages} names={this.state.names} />
and then to access these two bits of data (messages and name) from inside the <Chat /> component you could do the following:
const Chat = props => (
<div >
<ul>{props.messages.map((message, index) => <li key={message}>
From: { Array.isArray(props.names) ? props.names[index] : '-' }
Message: {message}</li>)}
</ul>
</div>
);
Hope this helps!
You have to pass them separately:
<Chat messages={this.state.messages} name={this.state.name} />

unable to get enter and get value in REACT.js

I am new to ReactJS and trying to build a sample application
I am unable to get enter the value in textbox and unable to get the value in alert. Am I doing something wrong. I have tried the example given on React.Js Form, but not working.
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {value:''};
this.OnSubmit = this.OnSubmit.bind(this);
}
OnSubmit(event){
alert('name value is : '+this.state.value);
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text" value={this.state.value} />
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;
please change :
<input type="text" value={this.state.value} />
to:
<input type="text" value={this.state.value} onChange = {this.onChange}/>
In your class, add the 'onChange' function:
onChange(e){
this.setState({
value: e.target.value
})
}
and in your constructor:
this.onChange = this.onChange.bind(this)
Edit 1:
please check my codepen here
Edit 2:
If you have too many inputs, you can use a function like this:(it's just a rough example, in real world I'll create a new component to handle this together)
//in your constructor
this.state = {}
//in class 'controlled component way'
createInput(num){
let inputArray = []
for(let i = 0; i < num; i ++){
inputArray.push(<input key = {i} name = {i} onChange = {this.onChange} value = {this.state[i] || ''} />)
}
return inputArray
}
onChange(e){
let key = e.target.name
let newState = {}
newState[key] = e.target.value
this.setState(newState)
}
// in your render function
return <div>
{this.createInput(100)}
</div>
check my codepen here for this example
and of course you can also do this using uncontrolled component.
controlled component and uncontrolled
You can either bind onChange event to your input or setState when submiting the value , you cant change the state like that
Change your code to something like this
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {value:''};
this.OnSubmit = this.OnSubmit.bind(this);
}
OnSubmit(event){
this.setState({value: this.refs.infield.value},()=>{
alert('name value is : '+this.state.value);
})
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text" ref = "infield"/>
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;
Hi to get the value add a name to the input and an onChange function to set the value to the state and then do what evere you want in onsubmit function
I cant write you a working code now because I'm using my phone but my this Will help
onfieldchange(e) {
this.setState({[e.target.name]: e.target.value});
}
onaSubmit(){
//do your code here
}
....
....
<input type="text" name="firstName" value={this.state.firstName} />
Hope this help you
There are two ways to handle form elements in reactjs:
Controlled and uncontrolled components(using refs).In controlled component approach ,you have to add the state of the input field to the input field value and onChange event to it, which is the one you are trying to do.Here is the working code.
import React, { Component } from "react";
class AddNewStudent extends Component {
constructor(props) {
super(props);
this.state = {
firstname:''
};
this.OnSubmit = this.OnSubmit.bind(this);
this.OnChange = this.OnChange.bind(this);
}
OnSubmit(event){
alert('name value is : '+this.state.firstname);
event.preventDefault();
}
OnChange(){
this.setState({
[e.target.name] : [e.target.value]
});
}
render(){
return(
<div>
<form onSubmit={this.OnSubmit}>
<fieldset className="Student-Form" id={this.props.id}>
<legend className="Legend">Add mew student</legend>
<div>
<div className="Block">
<div className="Float-Left">
<label>
<span>Name : </span>
<input type="text"
name="firstname"
value={this.state.firstname}
OnChange={this.OnChange}
/>
</label>
</div>
</div>
<div className="clearFix" />
<div className="Block">
<div className="Float-None">
<label>
<input type="submit" value="Save" />
</label>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
export default AddNewStudent;

Resources