Is inline-style best?

I’m familiar with Material-UI because I often use that. To use Material-UI, we often use inline-style.

//example
import React, {Component} from 'react';
class ExampleStyles extends Component {
render() {
return(
<div style={{
width: '100%',
height: 'auto',
textAlign: 'center'
background: '#F7F7F7'
}}>hoge</div>
)
}
}
//or add variable
class ExampleStyles2 extends Component {
render() {
const s = {
baseStyle: {
width: '100%',
height: 'auto',
textAlign: 'center'
background: '#F7F7F7'
} //if you wanna to need more style, you write style in variable here.
}
return(
<div style={s.baseStyle}>hoge</div>
)
}
}

but, I think, inline-style has problem. if we use inline-style, we should consider about responsive. inline-style is not convenient like media query. However, responsive design is most important. it is essential. this time, I suggest how to implement responsive grid in inline-style.

For this article, I made small sample. sample is here.

and, github repository is here.


How to implement to look like media query?

I think, There are so many type of implementation. most important point is how to bring window width and flag. this sample bring window size in state.

look this file.

I prepared to 2 type state. width, and check. width is window width size. if you change browser width size, window size is adapt.

In order to monitor it, I used componentWillUpdate. look this below.

...
componentWillUpdate() {
this.windowChange();
}
componentDidMount() {
this.initialSetting();
}
initialSetting() {
const windowSize = window.innerWidth;
const check = windowSize > 100
if (windowSize === this.state.width) {
return false;
} else {
if (windowSize > 768) {
this.setState({
check: true,
width: windowSize
})
} else if (windowSize < 768) {
this.setState({
check: false,
width: windowSize
})
}
}
}
windowChange() {
window.addEventListener('resize', () => this.initialSetting())
}
...

if window width size is over 768px, check is true. this true is Pc size. at the same time, false is mobile size. it is divide to mobile and pc here.

Finally, write DOM component.

render() {
const imageList = imgPath.map((img, i) => {
return (
<div style={
this.state.check ? s.gridBox_Pc : s.gridBox_Mobile
} key={uuid.v4()}>
<div style={s.imgBox}>
<img src={img.path} style={s.imgStyle} />
</div>
</div>
)
})
  return (
<main>
<header style={s.header}>
window width/{this.state.width}
</header>
<section style={s.container}>{imageList}</section>
</main>
)
}
if you change window size, it is adapt.

that’s all! How did you feel that? I think that if we implement inline-style only, it is so complex. I recommend to use css modules.

and have a good React.js life!