Search code examples
reactjsreact-component

React.js - How to access component by ID and call its method?


I have the following code in reactjs: How can I access any component like jquery using ID or there is some other solution?

Progressbar.jsx

class Progressbar extends Component {
  constructor() {
    super();
    this.state = { percentage: 0 };
  }
  progress(percentage) {
    this.setState({ percentage:percentage });
  }
  render() {
    // using this.state.percentage for the width css property
    ........
    ........
  }
};

FileUploader.jsx

class FileUploader extends Component {
  onUploadProgress() {
    // I want to call Progress1.progress( percentage_value )
  }
  render() {
    ........
    <Progressbar id="Progress1" />
    ........
    ........
  }
};

Solution

  • You are not thinking about the structure correctly. Progressbar does not need to maintain state at all:

    class Progressbar extends Component {
      render() {
        // using this.props.percentage for the width css property
      }
    };
    

    Keep state in FileUploader and pass it down to progress bar.

    class FileUploader extends Component {
      constructor() {
        super();
        this.state = { percentage: 0 };
      }
    
      onUploadProgress(percentage) {
        this.setState({ percentage: percentage });
      }
    
      render() {
        ...
        <Progressbar percentage={this.state.percentage} />
      }
    };