Skip to content Skip to sidebar Skip to footer

Reactjs - How To Complete Onclick Before Download - Href

I have a simple React button component that when clicked should retrieve and download data on the client browser. The problem I am experiencing is that the download is triggered an

Solution 1:

Make sure to bind this to your functions. In your constructor you can do:

constructor() {
    super();
    this.state = {
      users: ''
    };

    this.getUsers = this.getUsers.bind(this);
  }

or you can use the bind this function:

  getUsers = () => {
    const { userIds } = this.props;
    BatchRoleActions.getAllRoleUsers(userIds)
    .then((users) => {
      this.setState({ users: users});
      returnthis.state.users; // This should be removed, you can use this.state.users throughout this component.
    });
  }

Solution 2:

Why not get the user data in the componentDidMount lifecycle method? It doesn't look like it needs to be called onClick.

{
  // ...componentDidMount() {
    this.getUsers();
  }
  // ...render() {
    return (
      <divclassName="roles-export-button"><aclassName="button button-default"href={this.state.users}download={'roles.csv'}>Export Csv</a></div>
    )
  }
}

Solution 3:

How about handling the default "link" behaviour manually to get more control? Also you should probably try to access state after setState has been executed via its callback.

e.g.

getUsers(cb){
  const { userIds } = this.props;
  BatchRoleActions.getAllRoleUsers(userIds)
  .then((users) => {
    // note the callback of setState which is invoked// when this.state has been setthis.setState({ users: users }, cb);
  });
}

consthandleClick = () => {
  this.getUsers(() => {
    window.open(this.state.whatever)
  })
}

<span onClick={handleClick}>ExportCsv</span>

Post a Comment for "Reactjs - How To Complete Onclick Before Download - Href"