I'm creating simple form with a React component to send via axios.post
, so I'm trying to capture the input data but for some reason I get a
this is undefined
when trying to change the state.
I wrote name: 'hello', to just change the state to something an visualize in the form if it is working. Same as 'TryDescription'.
export default class Posts extends Component {
constructor(props){
super(props);
this.state = {
error: null ,
posts: [],
isLoaded: false,
name : null,
description: null,
}
}
static handleSubmit(event){
event.preventDefault();
console.log('hello');
};
handleInputchange(event){
console.log(event.target.value);
this.setState({
error : null ,
posts: [] ,
isLoaded:false,
name:'Hello',
description: 'TryDescription',
})
};
render() {
const { error, isLoaded, posts , name , description } = this.state;
return (
<div className="container">
<form onSubmit={Posts.handleSubmit}>
<div className="form-row">
<div className="form-group col-md-6">
<label htmlFor="name">Name</label>
<p>The name is:{name} </p>
<input onChange={this.handleInputchange} type="text" name='name' className="form-control" id="name" placeholder="Tittle"/>
</div>
<div className="form-group col-md-6">
<label htmlFor="description">Description</label>
<p>The description is:{description} </p>
<input onChange={this.handleInputchange} name="description" type="text" className="form-control" id="description" placeholder="Description"/>
</div>
</div>
<button type="submit" className="btn btn-primary">Create</button>
</form>
<div className="row">
{posts.map((post) =>
<div className="col-3" key={post.id} >
<div className="card" style={{width: 18 + 'rem'}}>
<div className="card-body">
<h5 className="card-title">{post.name}</h5>
<h6 className="card-subtitle mb-2 text-muted">Subtítulo</h6>
<p className="card-text">{post.description}</p>
<a href="#" className="card-link">Card link</a>
<a href="#" className="card-link">Another link</a>
</div>
</div>
</div>
)}
</div>
</div>
)
}
I would expect that doing:
this.setState({
error : null ,
posts: [] ,
isLoaded:false,
name:'Hello',
description: 'TryDescription',
})
name takes the 'Hello' string value but nothing.