0

I have been trying to implement a scenario where the data is passed from the child component to the parent component.

I am able to pass it but the screen doesn't persist due to the use of the form. I want to know how I can implement it while using form.

import React, { Component } from 'react';
import './App.css';

class FormComponent extends React.Component {
  render() {
    return (
      <form>
        <input type="text" name="caption" value={this.props.caption} onChange={(event) => this.props.changeCaption(event.target.value)} />
        <button onClick={this.props.onClick}>Add</button>
      </form>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      caption: ""
    }
  }

  changeCaption = (caption) => {
    this.setState({
      caption: caption
    })
  }

  handleClick = () => {
    console.log('Send to the list component', this.state.caption);
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <FormComponent 
            onClick={this.handleClick}
            caption={this.state.caption}
            changeCaption={this.changeCaption}
          />
        </header>
      </div>
    );
  }
}

export default App;

I would really appreciate some help with this. Thank You.

2 Answers 2

2

Hard to tell without testing but let me guess that it's link to "normal" behaviour of a form tag when submitted ....

Then you'll have to prevent the event to bubble, try this :

 handleClick = (e) => {
  e.preventDefault();
  console.log('Send to the list component', this.state.caption);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to "mark as resolved" by choosing an answer with the tick ;)
2

if you don't want to submit form on click you can add type="button" attribute to your button:

<button type="button" onClick={this.props.onClick}>Add</button>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.