0

 class Demo extends React.Component{
    constructor (){
      super();
      this.state = {
        list : ['car','map', 'house']
      }
    }
    inputValue(e){
      var x  = e.target.value;
      console.log(x)

    }
	addValue(){
      this.state.list.push();
      this.setState({list: this.state.list});
    }
	render(){
	  return(
	  <div>
		  <input onChange={this.inputValue} type="text"/>
        <ul>
          {this.state.list.map(item => (
            <li>{item}</li>
          ))}
        </ul>
		  <button onClick={this.addValue.bind(this)}>Add Element</button>
	  </div>
	  )
	}
  }
  ReactDOM.render(
    <Demo/>,
    document.getElementById('test')
  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="test"></div>

Using my code, how can i push the value from <input onChange={this.inputValue} type="text"/> in list : ['car','map', 'house']. I use for this addValue function, but i can't insert the x variable from inputValue function in push() from addValue function. How to do this using my code?

2
  • Hi Asking, please try my solution below and let me know if that helps :) Commented Aug 10, 2019 at 7:44
  • Thats great to hear. Happy coding :) Commented Aug 10, 2019 at 8:11

2 Answers 2

1

You need a state value for the text-input so that your addValue() function knows what to use when its time to add a new item. The text state will be updated with anything the user types.

Working demo: https://codesandbox.io/s/magical-feynman-fze1n

import React from "react";

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      text: "",
      list: ["car", "map", "house"]
    };
  }
  inputValue(e) {
    this.setState({
      text: e.target.value
    });
  }
  addValue() {
    const text = this.state.text;
    this.setState({ list: [...this.state.list, text] });
  }
  render() {
    return (
      <div>
        <input onChange={this.inputValue.bind(this)} type="text" />
        <ul>
          {this.state.list.map(item => (
            <li>{item}</li>
          ))}
        </ul>
        <button onClick={this.addValue.bind(this)}>Add Element</button>
      </div>
    );
  }
}
export default Demo;

Also, refrain from doing direct state-mutations like this.state.list.push(blah). This is against React principles and can lead to unwanted visual side-effects. If you need to reference an existing state, try to create a copy of it instead. In the case for you list, we use the spread-operator to create a shallow-copy and then added the new item to the array..

Sign up to request clarification or add additional context in comments.

Comments

0

Since React is all about small components and reusability consider breaking it up into two separate components... That way, if you need a form anywhere else you can reuse it...

Here is your Demo:

class Demo extends Component {
    state = { list: ['car', 'map', 'house'] };

    addItem = item => {
        this.setState({ list: [item, ...this.state.list] });
    };

    render() {
        return (
            <div>
                <Form addItem={this.addItem} />
                {this.state.list.map((item, index) => (
                    <div key={index}>{item}</div>
                ))}
            </div>
        );
    }
}

And here is the Form:

class Form extends Component {
    state = { item: '' };

    handleChange = event => {
        this.setState({ item: event.target.value });
    };

    handleSubmit = event => {
        event.preventDefault();
        this.props.addItem(this.state.item);
        this.setState({ item: '' });
    };

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input
                    type='text'
                    value={this.state.item}
                    onChange={this.handleChange}
                />
            </form>
        );
    }
}

Live Demo: https://stackblitz.com/edit/react-611uzp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.