Search code examples
react-nativestyled-components

TypeError: undefined is not a function (near '..._styledComponents.default.button...')


I am getting this error while using styled-components in react native project.

TypeError: undefined is not a function (near '..._styledComponents.default.button...')

Here is my code;

import styled from "styled-components";
const Buttonn = styled.button`
  background: white;
  width: 200px;
  height: 50px;
  bordercolor: black;
  font-size: 24px;
  color: black;
  text-align: center;
  &:hover {
    background: black;
    color: white;
  }
`;

function CourierDetails() {
  return (
  <Buttonn>Submit</Buttonn>
)}

Solution

  • styled.button works in React (web), if you want to style a Button in React-native, you have to use Button component provided by react-native.

    Also you have to import styled component from 'styled-components/native'

    import styled from 'styled-components/native'
    

    You can create a CustomButton component as Below

    import React from 'react';
    import styled from 'styled-components/native';
    
    const CustomButton = props => (
        <ButtonContainer
            onPress={() => alert('Hi!')}
            backgroundColor={props.backgroundColor}
        >
            <ButtonText textColor={props.textColor}>{props.text}</ButtonText>
    </ButtonContainer>
    );
    
    export default CustomButton;
    
    const ButtonContainer = styled.TouchableOpacity`
        width: 100px;
        height: 40px
        padding: 12px;
        border-radius: 10px;    
        background-color: ${props => props.backgroundColor}; 
    `;
    
    const ButtonText = styled.Text`
        font-size: 15px;
        color: ${props => props.textColor};
        text-align: center;
    `;
    

    Hope this answer helps you, Thank you!