How can I deal with a long className in React JSX?
@Imamudin Naseem solution with some code style improvements
I would suggest to improve code style and save classNames directly as a string
render() {
const classNames = [
'col-xs-6',
'col-xs-offset-3',
'col-md-4',
'col-md-offset-4',
'col-lg-2',
'col-lg-offset-5'
].join(' ')
return (
<h1 className={classNames}>
Some text
</h1>
);
}
You can also use classNames:
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
Maybe you can define some of your classes as variable, and reuse it.
Another Cleaner method will be to store the classNames in an array and join them.
render() {
const classNames = ['col-xs-6',
'col-xs-offset-3',
'col-md-4',
'col-md-offset-4',
'col-lg-2',
'col-lg-offset-5']
return (
<h1 className={classNames.join(' ')}>Some text</h1>
);
}
I usually just wrap the strings to multiple lines and concatenate them. Don't forget to add spaces at the end or beginning of the strings.
So for your example it would be:
render() {
return (
<h1 className={
'col-xs-6 ' +
'col-xs-offset-3 ' +
'col-md-4 ' +
'col-md-offset-4 ' +
'col-lg-2 ' +
'col-lg-offset-5'}>Some text</h1>
);
}
This way you it's also way easier to scan which classNames you have set.
Here is a great resource for some best-practice coding patterns, together with their respective ESLint or JSCS option.