Parsa
Parsa

Reputation: 119

React Form: Input Data Won't Display

Every time I click the button a post is being created and displayed

But the input data isn't showing up

import React, { Component } from 'react'

export default class App extends Component {
  state = {
    dataArr : [],
    isClicked: false,
    title : '',
    img : ''
  }

  handleSubmit = (e) => {
    e.preventDefault()
  }

  handleChange = (e) => {
    [e.target.name] = e.target.value
  }

  handleClick = () => {
    const copyDataArr = Object.assign([], this.state.dataArr)

    copyDataArr.push({
      title : this.state.title,
      img : this.state.img
    })

    this.setState({
      isClicked : true,
      dataArr : copyDataArr
    })

  }

  render() {
    console.log(this.state.title)
    return (
      <div>
          <form onSubmit={this.handleSubmit}>
          <input type="text" name="title"  placeholder="Title.." onChange={this.handleChange}/>
          <input type="text" name="img" placeholder="Image.." onChange={this.handleChange}/>
          <button onClick={this.handleClick}>SUBMIT</button>
          </form>
          { this.state.isClicked ? 
              this.state.dataArr.map(
                (post, index) => { 
                  return(
                    <div class="div">
                      <h1>title: {post.title}</h1> 
                      <img src={post.img} alt="ohno"/>
                    </div> 
                  )

                }
              ) 
              : null }
      </div>
    )
  }
}

Created an empty array on state and copied the array and pushed in the input values. What am I doing wrong?

Need the onChange to work and the input data to display

Trying to learn forms in react. Hope someone can help out

Upvotes: 1

Views: 2463

Answers (2)

Muljayan
Muljayan

Reputation: 3886

You have to add a value attribute to the input tag and pass the state value.

<input type="text" name="title" value={this.state.title}  placeholder="Title.." onChange={this.handleChange}/>

Your handle change function should be as follows

  handleChange = (e) => {
    this.setState({[e.target.name] : e.target.value});
  }

Upvotes: 0

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

Your handleChange function is not updating state with the data you enter to the inputs. Looks like you might have forgotten to call this.setState(). Try this :

  handleChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value
    })
  }

Also here is a sandbox with the working code: https://codesandbox.io/s/distracted-darkness-xp3nu

Upvotes: 1

Related Questions