'Using pseudo-classes in React component
In my React component, I have a form with multiple input fields. In the CSS classes that I'm working with, there's an "invalid" pseudo-class that should highlight the field if its value is invalid. Currently, the input fields do not have any classes defined in my component. They're using the default styling that comes from the CSS file.
class MyForm extends Component {
render() {
return(
// There's more code here. Not showing to keep things simple
<input type="text" name="someProperty" value={myObject.someProperty} onChange={e => this.someFunction(e)} />
);
}
}
How do I actually use this -- meaning, how do I set the input field to invalid? I tried simply adding "invalid" to its CSS class but it didn't work.
This is what I tried with no results:
<input type="text" name="someProperty" className={showInvalid} value={myObject.someProperty} onChange={e => this.someFunction(e)} />
UPDATE:
Doing a bit more research on pseudo-classes, they do NOT go into the class. So in HTML, the input field would simply appear as below:
<input name"someProperty" invalid />
Solution 1:[1]
If I understand correctly, that is what you're looking for
className={`${this.state.showInvalid} ? 'invalidCssClassName' : 'nonInvalidCssClassName'`}
That means you should store somewhere (state or props) the value which will be responsible for evaluating the class name. In that case when showInvalid is evaluated to true, CSS class will be invalidCssClassName otherwise nonInvalidCssClassName
Solution 2:[2]
var NumberInput = React.createClass({
render: function() {
return <input type="number" pattern="[0-9]+([\,|\.][0-9]+)?" step="0.01" title="This should be a number with up to 2 decimal places." placeholder="Price" />;
}
});
ReactDOM.render(
<NumberInput />,
document.getElementById('container')
);
input:invalid {
background-color: #ff3333;
}
input:valid {
background-color: transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jmac |
| Solution 2 | Babanila |
