Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create "TouchableOpacity" for ReactJS without using react-native-web

I'd like to create a wrapper component that will behave like react- natives <TouchableOpacity/> without using react-native-web.

I'm thinking something that manages state and using inline styles that transitions from .5 to 1 for opacity with a setInterval or should it be a css transition.

Is there anything already out there?

What's the best approach for this?

like image 856
garrettmac Avatar asked Jun 22 '18 20:06

garrettmac


1 Answers

You can achieve this affect with css transitions and using state to track when the user is clicking the button:

class App extends React.Component {

  state = {
    touched: false
  }
  
  toggleTouched = () => {
    this.setState( prevState => ({
      touched: !prevState.touched
    }));
  }
  
  handleMouseUp = () => {
    // Handle smooth animation when clicking without holding
    setTimeout( () => {
      this.setState({ touched: false });
    }, 150);
  }
  
  render () {
    const { touched } = this.state;
    const className = touched ? 'btn touched' : 'btn';
    return (
        <button 
          className={className}
          onMouseDown={this.toggleTouched}
          onMouseUp={this.handleMouseUp}
        >
          Touch Here
        </button>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
.btn {
  background: #ededed;
  padding: 10px 15px;
  border: none;
  outline: none;
  cursor: pointer;
  font-size: 15px;
  
  opacity: 1;
  transition: opacity 300ms ease;
}

.touched {
  opacity: 0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
like image 141
Chase DeAnda Avatar answered Oct 16 '22 05:10

Chase DeAnda