Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Share variables between components

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?

like image 238
Anh Tuan Nguyen Avatar asked Jun 06 '26 04:06

Anh Tuan Nguyen


1 Answers

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

like image 145
Oleksandr T. Avatar answered Jun 08 '26 18:06

Oleksandr T.