简体   繁体   中英

Reactjs Add spinner when click button

Here is my code:

<ButtonOrder
  style={{ background: values.sideNB ? NBColor : NSColor }}
  type="button"
  disabled={isPlacingOrder}
  onClick={handleSubmit}
>
  {isPlacingOrder ? "Đang đặt lệnh" : "Đặt lệnh"}
</ButtonOrder>;

How to change to add spinner instead of text when you click on any button with type "button"

If you just wanna use spinner instead of text ( Đang đặt lệnh ), here a way to do.

 const ButtonOrder = ({ children, ...rest }) => { return <button {...rest}>{children}</button>; }; const Spinner = () => ( <img src="https://loading.io/spinners/microsoft/index.svg" class="zoom2" height="20"/> ) class App extends React.Component { state = { isPlacingOrder: false }; handleSubmit = () => { this.setState( { isPlacingOrder: true }, () => { setTimeout(() => { this.setState({ isPlacingOrder: false }); }, 2000); } ); } render() { const { handleSubmit, state } = this; const { isPlacingOrder } = state; return ( <ButtonOrder type="button" disabled={isPlacingOrder} onClick={handleSubmit}> {isPlacingOrder ? <Spinner /> : "Đặt lệnh"} </ButtonOrder> ); } } ReactDOM.render(<App />,document.getElementById("app"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

You can check out this implementation for your issues. If you are using redux or any API call while the loader should be visible (toggle), then that would be simple, but for your current case you can follow this: https://reactjsexample.com/the-easiest-way-to-manage-loaders-errors-inside-a-button/

If you are using material or semantic, then you can check their docs with "spinners" you'll get there.

this.state = {
  disabled: false,
  processing: false
}


<TouchableWhatever disabled={this.state.disabled} onPress={this.click.bind(this)}>
  { this.state.processing 
      ? <ActivityIndicator />
      : <Text>Click me</Text>
  }
</TouchableWhatever>


click() {
  this.setState({
    disabled: true, 
    processing: true
  });
  // login, respond
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM