How to style input tag without class with JSS

8.5k views Asked by At

I am using the react-select component on my app. I am also only styling my app with JSS. My issue is that since react-select is an npm package, I don't have the capability to modify class names in the component. So there is an input in there that I need to target with my styles.

<div class="Select-input"><input type="text" name="style-me" /></div>

And my JSS is a little something like this:

jss.setup(preset());

const stylus = {
   'Select-input': {
       background: 'red'
   }
}

const { classes } = jss.createStyleSheet(stylus).attach();

What do I need to do in JSS to style that child input tag?

3

There are 3 answers

1
Cave Johnson On BEST ANSWER

According to this answer, you can pass in a class name for react-select. The rest of my answer shows how to target child elements.


I checked the github page for JSS here:
https://github.com/cssinjs/jss

They have a live example for nested CSS rules here:
https://github.com/cssinjs/examples/blob/gh-pages/plugins/jss-nested/simple/app.js

In the code to target a nested <button> element, it uses a property named & button. Notice the space between the ampersand and button. So for your specific code, you can target the <input> like this:

jss.setup(preset());

const stylus = {
   'Select-input': {
       background: 'red',
       '& input': {
            /* your input styles here */
       }
   }
}

const { classes } = jss.createStyleSheet(stylus).attach();
1
ioseph On

Assuming you're referring to this package:

https://github.com/JedWatson/react-select

You can in fact pass in className as a prop

0
Oleg Isonen On

You have always at least 2 ways:

  1. Pass the generated class name

Use JSS as you should by default, avoid unscoped class names. Use generated class name and pass it to the component you want to use

const {classes} = jss.createStyleSheet({
  input: {background: 'red'}
}).attach()


<Input className={classes.input} />
  1. Use scoped global selector

If its impossible to pass a class name, you can still have a locally scoped global selector

const {classes} = jss.createStyleSheet({
  container: {
    '@global': {
      input: {background: 'red'}
    }
  }
}).attach()

<div className={classes.container}>
  <Input />
</div>