Day 3: Styling Components
On the third day of learning ReactJS, I learnt ways to style components in React using External and Inline CSS using ‘style’ attribute.
External CSS and inline styling in React are similar to their counterparts in HTML but have some key differences and considerations:
External CSS:
External CSS involves writing styles in a separate CSS file and linking it to the HTML/JSX file. In React, we import external CSS files into your components using the import statement. Once imported, we can apply classes or IDs defined in the CSS file to your JSX elements using the className attribute (using camelCase). This allows for easy maintenance and reuse of styles across multiple components. Styles defined in external CSS files can affect the entire application, which can lead to unintended style conflicts.
//Second.js
import './Second.css'
export const Second = () =>{
return (
<h1 className = "heading2">This is my second component</h1>
)
}
export const Second2 = () =>{
return(
<>
<h1>This is my another second component</h1>
<p>Hello there!</p>
</>
)
}
//Second.css
:root{
--bg-primary: #010101;
--text-primary: #fff;
--size: 40 px;
}
.heading2{
background-color: var(--bg-primary);
color: var(--text-primary);
font-size: var(--size);
}
Inline Style Attribute:
Inline styling involves applying styles directly to individual HTML/JSX elements using the style attribute. In React, you define styles as JavaScript objects within the component's JSX. You apply these styles by passing the JavaScript object to the style attribute of the JSX element. This allows for dynamic styling based on component state or props. It also voids issues with global scope and style conflicts since styles are scoped to specific elements. However, it overrides other styles, including styles applied by external CSS files or CSS frameworks, which can lead to unexpected behavior.
领英推荐
const First = () =>{
const h1Style={
backgroundColor: "#589320",
color:"yellowgreen"
}
return (
<h1 style = {h1Style}>This is my first component</h1>
)
}
export default First
Comparison with HTML:
External CSS:
The usage of external CSS in React is quite similar to HTML. Both involve linking external CSS files to apply styles globally or to specific elements using classes or IDs.
//react component
import './Second.css'
//HTML equivalent
<link rel="stylesheet" type="text/css" href="Second.css">
Inline Style Attribute:
While inline styling is also possible in HTML using the style attribute, the syntax and usage in React are slightly different due to JSX's nature. In React, styles are defined as JavaScript objects rather than strings, allowing for dynamic styling and better integration with component logic.
//react component
<h1 style = {h1Style}>This is my first component</h1>
//HTML Equivalent
<h1 class="h1-style">This is my first component</h1>