Using Styled Components in functional React components

Viewed 337

(I hope and assume that there is a simple answer to this question, but I could not find it in the docs)

I've just converted a React project to use Styled Components, and love the DRYness and reusability. But, I've not yet figured out the syntax for using styled components in existing functional components that do other work too.

Here's one example:

const StyledSearchBarPane = styled(Pane)`
    grid-area: search-bar;
`;

const SearchBarPane = () => {
  const {query} = useContext(panelContext);
  let [newQuery, setNewQuery] = useState(query);
  return (
    <StyledSearchBarPane>
      <Bar>
        <SearchInput newQuery={newQuery} setNewQuery={setNewQuery}/>
      </Bar>
    </StyledSearchBarPane>
  );
};

How can I avoid naming StyledSearchBarPane? It's only used once -- in SearchBarPane -- and I'd rather it were simply part of the latter's definition.

1 Answers

Yes you can.

Basically what you need to do is use your component as you would normally do and if you want to use a local style on the component without creating one you can use a Wrapper like you did.

But the change is, instead of exporting your component you export the wrapper. Then your component will receive as props className and you need to put it where you want to apply thoses style, in the example since it's globally you put in the root element.

If you don't put the className props it won't style anything.

const SearchBarPane = ({className}) => {
  const {query} = useContext(panelContext);
  let [newQuery, setNewQuery] = useState(query);
  return (
    <div className={className}>
      <Bar>
        <SearchInput newQuery={newQuery} setNewQuery={setNewQuery}/>
      </Bar>
    </div>
  );
};

const StyledSearchBarPane = styled(SearchBarPane)`
    grid-area: search-bar;
`;


export default StyledSearchBarPane;

https://styled-components.com/docs/advanced

Related