简体   繁体   中英

--How do I convert jQuery code in my React Component?

I need to update the CSS, and naturally I used jQuery, but I'm told not to use jQuery with React.

How would I do this properly. I can add more code if needed. I'm simply toggling the bottom border of a div

  toggleMarker () {
    if (this.state.previous && (this.state.current !== this.state.previous)) {
      $('#nav_' + this.state.previous).css("border-bottom", '');
    }
    if (this.state.previous !== this.state.current) {
      $('#nav_' + this.state.current).css("border-bottom", this.color);
    }
    this.setState({previous: this.state.current});
  }

You can manipulate components style inline and you can give conditions according to state variables.

Example

 render(){
    return(
        <div style={{ borderBottom: ((this.state.previous && (this.state.current !== this.state.previous)) ? 'none' : 1) }}>
            // ...
        </div>
   )
}

When it comes to react, there are many ways to style a component including inline styles, define styles in css and import, using styled components and also using some small JS libraries eg classnames .

classnames supports any JS expression as class name to your HTML element. You can explore more using above link.

Just a simple example:

import styles from './yourcss.css'
import { classnames } from './classnames/bind'
const cx = classnames.bind(styles)

<div className={cx('divStyle')}>
</div>

I would suggest to have inline CSS with reference from variable in the state. consider this,

//define state
this.state={
    toggleState : false}

//have toggler function   
togglerFunction(){
    var temp = this.state.toggleState
    this.setState({
         toggleState : !temp})
}

//in render you can have your element like this
render(){
...
//start of your element suppose a div
{this.state.toggleState == false ? <div style=        
{{borderBottom:"YourValueForFalseHere"}}></div>:<div style=                
{{borderBottom:"YourValueForTrueHere"}}></div>}
//...End of your element
...
}

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