In the bellow React component, I'm using styled-components library for the purpose of styling.
import React from 'react'
import jsonResponse from '../data'
import styled from 'styled-components'
const StyledUl = styled.ul`
width: 100%;
`
const StyledLi = styled.li`
width: 100%;
/* Tablet View */
@media (min-width: 45.563em) and (max-width: 61.312em) {
width: 50%;
}
/* Desktop View */
@media (min-width: 61.313em) {
width: 33.33%;
}
`
const TextContainer = styled.div`
text-align: left;
`
const Btn = styled.button`
width: 26%;
@media (min-width: 45.563em) and (max-width: 61.312em) {
width: 42%;
}
@media (min-width: 61.313em) {
width: 42%;
}
`
function MyList ({ setID }) {
const list = jsonResponse.characters.map((item) => {
return (
<StyledLi key={item.id}>
<TextContainer>
<h3>{item.name}</h3>
<p>{item.details.short}</p>
</TextContainer>
<Btn onClick={() => setID(item.id)}>Read more</Btn>
</StyledLi>
)
})
return (
<StyledUl className='cf'>
{list}
</StyledUl>
)
}
export default MyList
Now I want to cut the styling part and put it in a separate file called myList-styling.js and import it in to my component MyList.jsx, but I'm not sure how.
Could you please help?
It's pretty easy. First we have to answer this question.
What are styled components? They're just basically some components, right?
So we can export them from a file and import them in another!
Just create another file (Let's name it MyList.styled.js
) and export your styled components from it. Then all you need to do is to import them in MyList.js
.
// mylist-styling.js
export const StyledUl = styled.ul`
width: 100%;
`
export const StyledLi = styled.li`
width: 100%;
/* Tablet View */
@media (min-width: 45.563em) and (max-width: 61.312em) {
width: 50%;
}
/* Desktop View */
@media (min-width: 61.313em) {
width: 33.33%;
}
`
export const TextContainer = styled.div`
text-align: left;
`
export const Btn = styled.button`
width: 26%;
@media (min-width: 45.563em) and (max-width: 61.312em) {
width: 42%;
}
@media (min-width: 61.313em) {
width: 42%;
}
`
and just import them here:
// MyList.js
import React from 'react'
import jsonResponse from '../data'
import styled from 'styled-components'
import {styledUI, StyledLi, TextContainer, Btn} from './MyList.styled'