1

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" />
    ........
    ........
  }
};
Saifullah khan
  • 686
  • 11
  • 19
  • 1
    Why don't you just pass the value down as `props`? You should really forget the way jquery handles things and start to think in react. – Sulthan Mar 07 '18 at 21:28
  • check out this question: https://stackoverflow.com/questions/37949981/call-child-method-from-parent – Egor Egorov Mar 07 '18 at 21:28

2 Answers2

3

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} />
  }
};
Sulthan
  • 128,090
  • 22
  • 218
  • 270
1
  • ProgressBar can be a stateless component.
  • The value of ProgressBar is updated from the state of its parent.

There is a demo:

const ProgressBar = props => (
  <div style={{ display: 'block', width: `${props.percentage}%`, height: 20, backgroundColor: '#ccc' }} />
);

class App extends Component {
  state = {
    percentage: 0,
  }

  componentDidMount() {
    setInterval(() => {
      let nextPercent = this.state.percentage+1;
      if (nextPercent >= 100) {
        nextPercent = 0;
      }
      this.setState({ percentage: nextPercent });
    }, 100);
  }

  render() {
    return (
      <div>
        <h2>Progress bar</h2>
        <ProgressBar percentage={this.state.percentage} />
      </div>
    );
  }
}

There is the fully functional codesandbox demo https://codesandbox.io/s/6y9p69q0xw

FisNaN
  • 2,517
  • 2
  • 24
  • 39