Home > Software design >  Component is not being styled according to className
Component is not being styled according to className

Time:01-04

For some reason setting className is not styling my property:

export default class MyComponent extends Component {
  render() {
    return(
      <div className={styles.example}>
     </div>
    )
  }
}

const styles = StyleSheet.create({
  example: {
    background: 'black',
    width: '100px',
    height: '100px'
  }
})

It just renders something like

<div >
</div>

With no styling information (there is no CSS rule for the ""class"" 175)

Why is it not (as I expect) ending up with a name like styles__example___2w27N with CSS rules specified in the browser

.styles__example___2w27N {
    background-color: 'black';
    height: 100px;
    width: 100px;
}

How do I get my CSS to be applied?


If I use style={styles.example} (instead of className) I actually get this error:

The style prop expects a mapping from style properties to values, not a string.

I would prefer to use className though because

  • I have specified hover and active styles, does style work with those?
  • I want to manually add and override some styles inline

CodePudding user response:

You should be using the <View> component instead of the <div> component, as that will map the <View> component to the native view UI components for each specific platform that you're using (ie: <div> for web, android.view for android, etc.) and not the <div> element directly.

With that, the <View> element and other react-native core components are designed to work with StyleSheet. You should be applying your style to the style prop which all core components have, and not the className prop:

<View style={styles.example}>
</View>

When the above is viewed on the web, you'll see a <div> being used in the source, but on other platforms you'll see other native view UI types being used.

CodePudding user response:

Stylesheet refers to React Native... are you doing react-js or react native?

Assuming you are doing react-js (because of the div), there is no such thing as stylesheet in react-js...

export default class MyComponent extends Component {
  render() {
    return(
      <div className={styles.example}>
     </div>
    )
  }
}

const styles = {
  example: {
    background: 'black',
    width: '100px',
    height: '100px'
  }
}

I think you copied the code from a react-native document instead of the react-js...

  •  Tags:  
  • Related