0

I created a component. Code can be seen here: http://codepen.io/anon/pen/zZmyyd

class Add extends React.Component  {
  constructor () {
    super();
    this.state = {
      inItems: ["aaa", "bbb", "ccc", "ddd"]
    } 
     this.state.items= this.state.inItems;
  }


  add () {
        const currentItems = this.state.inItems,
            newVal = this.refs.inputVal.value;
        currentItems.push(newVal);
        this.setState({
            items: currentItems, 
            value: newVal 
        });
  }

  render () {
    return (
        <div>
        <input type="text"  ref="inputVal"/>
            <button type="button" onClick={this.add.bind(this)}>Add</button>
            <List items= {this.state.items} />
         </div>
     )
  }
}

class List extends React.Component {
    render () {
        return (
            <ul>
                {
                    this.props.items.map(function(item) {
                        return <li key={item}>{item}</li>
                    })
                }
            </ul>
        )
    }
}


ReactDOM.render(
  <Add />,
  document.getElementById('root')
);

How can I add value from Addnews component?

class Addnew extends React.Component {
    constructor () {
        super();
    }

    saveit () {
        const currentItems = this.state.inItems,
            newVal = this.refs.inputVal.value;
        currentItems.push(newVal);
        this.setState({
            items: currentItems, 
            value: newVal 
        });
    }

    render () {
        return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
    }
}
2
  • Can you add more explanation Commented Mar 29, 2017 at 9:56
  • You can use redux or similar. Commented Mar 29, 2017 at 10:02

1 Answer 1

1

You have to render the Addnew component in Add component.

And then pass the add function as props to Addnew Component:

render () {
    return (
        <div>
        <input type="text"  ref="inputVal"/>
            <button type="button" onClick={this.add.bind(this)}>Add</button>
        <List items= {this.state.items} />
        <Addnew add={this.add.bind(this)} />
     </div>
 )
}

And in Addnew component:

class Addnew extends React.Component {
    constructor () {
        super();
    }

    saveit () {
       this.props.add();
    }

    render () {
        return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
    }
}

here's the modified code: http://codepen.io/anon/pen/OpBdpV?editors=0010#0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.