React supports inline CSS styles for elements. Styles are supplied as a style prop with a JavaScript object.
// Passing the styles as an objectconst color = {color: 'blue',background: 'sky'};<h1 style={color}>Hello</h1>// Passing the styles with an inline object, as a shorthand<h1 style={{ color: 'red' }}>I am red!</h1>
In React, style names are written in “camelCase”, unlike in CSS where they are hyphenated. In most cases, style values are written as strings. When entering numeric values, you don’t have to enter px because React automatically interprets them as pixel values.
// Styles in CSS:// font-size: 20px;// color: blue;// Would look like this style object in React:const style = {fontSize: 20,color: 'blue',};
CSS Modules provide a way to scope styles locally to individual React components by automatically transforming class names into unique identifiers at build time. This prevents unintended style conflicts across the application and eliminates the need for complex naming conventions.
By separating styles into dedicated module files, components maintain better organization and modularity. Each component’s styles remain isolated, making it easier to locate and maintain styling logic without worrying about class name collisions.
/* Button.module.css */.button {padding: 10px 20px;background-color: blue;color: white;}/* Button.js */import styles from './Button.module.css';function Button({ children }) {return (<button className={styles.button}>{children}</button>);}
In React, form fields are considered either uncontrolled, meaning they maintain their own state, or controlled, meaning that some parent maintains their state and passes it to them to display. Usually, the form fields will be controlled.
The example code shows an uncontrolled and controlled input.
const uncontrolledInput = <input />;const controlledInput = (<input value={stateValue} onChange={handleInputChange} />);
A controlled form element in React is built with a change handler function and a value attribute.
const controlledInput = (<input value={stateValue} onChange={handleInputChange} />);