soundust
soundust

Reputation: 45

React jsx conditional styling of <input/> component

I am conditionally styling my <input/> (standard HTML) component. I am passing inline JSX style as a style prop:

render() {
  return (
    <>
      <input
        type="text"
        style={{
          width: "100%",
          paddingLeft: "8px",
          paddingTop: "6px",
          paddingBottom: "6px",

          border: this.state.error
            ? "2px solid red"
            : this.state.value
            ? "2px solid #2684ff"
            : "2px solid hsl(0, 0%, 80%)",
          outline: "0px",

          "&:hover": {
            border: "2px solid green"
          }
        }}
        placeholder={this.props.placeholder}
        onChange={this.handleInput}
        onFocus={this.checkErrors}
        value={this.state.value}
        onBlur={this.sendData}
      />

      {this.state.error ? (
        <div className="errorMsg"> {this.props.errorMsg} </div>
      ) : null}
    </>
  );
}

My conditional styles work, and <input/> border colour changes based on this.state.error and this.state.value, however I can't get '&:hover' style to work. I have checked my .css and there is nothing overriding the style passed as props.

I have tried another approach, where I conditionally set className for my <input/> and define style in external .css file. It works and I can change border colour with:

    input[type="text"]:hover {
      border: 2px solid pink;
    }

However, I would like to make this work in inline JSX. Why does my style for '&:hover': { ... } not work?

Upvotes: 2

Views: 11632

Answers (2)

Thanh Thanh
Thanh Thanh

Reputation: 188

The "&" operator mean the current selector in preprocessing language like sass:

input {
  &:hover {
    background: red;
  }
}

Will compile to:

input:hover {
  background: red;
}

But you will have to use sass or styled component to use that sync tax.

Upvotes: 3

gadi tzkhori
gadi tzkhori

Reputation: 612

Pseudo css selectors don't work in inline style.btw I would not recommend any of the js solution in the comments above .you need a more a robust css solution to handle all kind of pseudo selectors. Your options are:

  1. Use css in js solution like styled-components.https://styled-components.com/

  2. Use regular css or scss and condionaly switch classNames.You can utilize classnames library for easier experience.https://www.npmjs.com/package/classnames

  3. Render style tag above your input and put your input styles there.quite bad practice and ugly.

Upvotes: 0

Related Questions