3

I have three Components. App is the Parent component. Tools and DrawingBoard are child Components. I want to transfer Data between the Tools and DrawingBoard Component.

export default class App extends  Component{
  getFormData(name, value){
   //empty so far
}
 render(){
   return(
    <div className="main-container">
        <DrawingBoard  styledata={???} />
        <Tools  data={this.getFormData.bind(this)}/>
   </div>
  );
}

I pass the function getFormData as a property to Tools to get its data. Now I want to pass name and value, preferably as an associative array or object with arr["name"] = value as a property to DrawingBoard. How can I do that?

1 Answer 1

4

You can use state in App component which you can change it inside Tools and new state pass to DrawingBoard,

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      styledata: {}
    };
  }

  getFormData(name, value) {
    this.setState({
      styledata: { [name]: value }
    })
  }

  render() {
    return <div className="main-container">
      <DrawingBoard styledata={ this.state.styledata } />
      <Tools data={ this.getFormData.bind(this) } />
    </div>
  }
}

class Tools extends React.Component {
  getData() {
    // Load data
    // 
    this.props.data('color', 'red');
  }

  render() {
    return <div>
      <button onClick={ this.getData.bind(this) }>Change Data</button>
    </div>
  }
}

class DrawingBoard extends React.Component {
  render() {
    return <div>
      <h1 style={ this.props.styledata }>DrawingBoard</h1>
    </div>
  }
}

Example

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

1 Comment

using this.getData.bind(this) directly reduce the performance of the app, as it re-render the component, therefore use 'this.getData = this,getData.bind(this)' in the constructor. For more information visit ' youtube.com/… '

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.