It is important to set default styles to React components to maintain a consistent and visually appealing user interface. React offers different ways to style components and JSX elements. Let’s explore some of them.
Inline styles allow us to style JSX elements directly within our component-using objects. To style a JSX element, first, we need to create an object containing CSS properties and their values as a key-value pair. Then, we can set the default style for the JSX element by passing an object inside the style
prop.
import React from "react"; const ShoppingCart = () => { // Define default style for p element const pStyle = { color: "white", backgroundColor: "red", margin: "10px", fontSize: "36px", }; return ( <div> <p style={pStyle}>Shopping Cart</p> </div> ); }; export default ShoppingCart;
In the example above, pStyle
(Line 5) is an object containing CSS properties and their values. When the ShoppingCart
component is rendered, the styles defined in the pStyle
object are applied to the p
element in the component (Line 13).
We can also style the component directly by passing down the CSS style object as props. Let’s see this with the help of the following example:
import React from "react"; const ShoppingCart = ({style}) => { return ( <div style={style}> <p>Shopping Cart</p> </div> ); }; export default ShoppingCart;
In the code above, componentStyle
is an object containing CSS properties and its values. We pass this style object as a prop to the ShoppingCart
component. In this way, the ShoppingCart
component is rendered by applying all the styles defined in the componentStyle
object.
We can use the same style object to style different components or to style different JSX elements within the component.
Like the global stylesheet, we can also create a separate style object, export it globally, and later use it to style other components.
export const componentStyle = { color: "white", backgroundColor: "red", margin: "10px", fontSize: "36px", };
To use a style object globally, first, we need to create a style object, componentStyle
, in the Style.js
file, make it exportable, and then import it into the ShoppingCart
component. We use the style
prop to apply properties of the style object in the main div
of the ShoppingCart
component. When the App
component renders the ShoppingCart
component, it applies all the styles defined in the componentStyle
object. Similarly, we can use the componentStyle
globally in any number of components.
Note: In the above SPA widget, we use the version
18.2.0
of React.
Free Resources