Let's say I'm rendering this component in React JSX:
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>
);
}
The classes trigger my JS linter as a line that's too long, and it's very hard to read. How can I separate a long className
property in a React component into multiple lines without breaking JSX syntax or triggering a different error in a JS linter? (I'm using ESLint).
Adding a single class name import React from 'react'; import './styles. css'; function App(){ return ( <div className="container"> <h1>Hello rock!! </h1> </div> ) } export default App; If you want to add multiple class names, you can add it to the className attribute by separating with spaces.
Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With