Search code examples
javascriptcssreactjsstyled-components

material-ui-search-bar as Styled Component


I was using material-ui-search-bar like this and it worked fine:

<SearchBar
         style={{
          margin: '0 auto',
          maxWidth: 800,
        }}
        />

However, when I change it to styled components, the styling doesn't work properly and the search bar extends to the whole screen.

export const StyledSearchBar = styled(SearchBar)`
  margin: 0 auto;
  max-width: 800;
`;

I also tried using maxWidth. How can I fix this?

I am unable to create a sandbox due to MUI theme errors.


Solution

  • material-ui-search-bar requires material-ui version 1.0 or above.
    You need the following dependencies for your code to work:

    "@material-ui/core": "4.9.11",
    "@material-ui/icons": "4.9.1",
    "material-ui": "1.0.0-beta.47",
    "material-ui-search-bar": "1.0.0-beta.14",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.3.0",
    "styled-components": "5.1.0"
    

    Regarding the width - node that with styled component you neet to set the px on the width:

    export const StyledSearchBar = styled(SearchBar)`
      margin: 0 auto;
      max-width: 800px;
    `;
    

    And here is the updated codesandbox: https://codesandbox.io/s/styled-material-ui-search-box-example-4mpoc