I am new to ReactJS and JSX and I am having a little problem with the code below.
I am trying to add multiple classes to the className
attribute on eac
Just adding, we can filter out empty strings.
className={[
'read-more-box',
this.props.className,
this.state.isExpanded ? 'open' : 'close',
].filter(x => !!x).join(' ')}
I bind
classNames
to the css module imported to into the component.
import classNames from 'classnames';
import * as styles from './[STYLES PATH];
const cx = classNames.bind(styles);
classnames
gives the ability to declare className
for a React element in a declarative way.
ex:
<div classNames={cx(styles.titleText)}> Lorem </div>
<div classNames={cx('float-left')}> Lorem </div> // global css declared without css modules
<div classNames={cx( (test === 0) ?
styles.titleText :
styles.subTitleText)}> Lorem </div> // conditionally assign classes
<div classNames={cx(styles.titleText, 'float-left')}> Lorem </div> //combine multiple classes
If you wanna use a double conditional css module is always somehow confusing so i would advise you to follow this pattern
import styles from "./styles.module.css"
const Conditonal=({large, redColor}) => {
return(
<div className={[large && styles.large] + [redColor && styles.color]>
...
</div>
)
}
export default Conditonal
and if its just one conditonal statement with two class name, use this
import styles from "./styles.module.css"
const Conditonal=({redColor}) => {
return(
<div className={styles.large + [redColor && styles.color]>
...
</div>
)
}
export default Conditonal
I know this is a late answer, but I hope this will help someone.
Consider that you have defined following classes in a css file 'primary', 'font-i', 'font-xl'
<h3 class = {` ${'primary'} ${'font-i'} font-xl`}> HELLO WORLD </h3>
would do the trick!
For more info: https://www.youtube.com/watch?v=j5P9FHiBVNo&list=PLC3y8-rFHvwgg3vaYJgHGnModB54rxOk3&index=20
Using facebook's TodoTextInput.js example
render() {
return (
<input className={
classnames({
edit: this.props.editing,
'new-todo': this.props.newTodo
})}
type="text"
placeholder={this.props.placeholder}
autoFocus="true"
value={this.state.text}
onBlur={this.handleBlur}
onChange={this.handleChange}
onKeyDown={this.handleSubmit} />
)
}
replacing classnames with plain vanilla js code will look like this:
render() {
return (
<input
className={`
${this.props.editing ? 'edit' : ''} ${this.props.newTodo ? 'new-todo' : ''}
`}
type="text"
placeholder={this.props.placeholder}
autoFocus="true"
value={this.state.text}
onBlur={this.handleBlur}
onChange={this.handleChange}
onKeyDown={this.handleSubmit} />
)
}
You can create an element with multiple class names like this:
<li className="class1 class2 class3">foo</li>
Naturally, you can use a string containing the class names and manipulate this string to update the class names of the element.
var myClassNammes = 'class1 class2 class3';
...
<li className={myClassNames}>foo</li>