React, a powerful JavaScript library for building user interfaces, offers developers the flexibility to create and style components in various ways.
One of the most common UI elements is the button, and in React, styling buttons can be achieved through different methods, each with its own advantages.
In this article, we'll explore how to apply react button style effectively, ensuring that our buttons not only look good but also function seamlessly across different browsers and devices.
Before diving into styling, let’s set up a basic react button component. This will serve as the foundation for our styling examples throughout the article.
1import React from "react"; 2 3const Button = ({ buttonText, onClick, disabled }) => { 4 return ( 5 <button onClick={onClick} disabled={disabled}> 6 {buttonText} 7 </button> 8 ); 9}; 10 11export default Button;
Here, we’ve created a functional component named Button that accepts buttonText, onClick, and disabled as props. The 'disabled' attribute can be used to make buttons look inactive and prevent onClick handlers from firing. Now, let’s apply some inline styles to this button component.
1const Button = ({ buttonText, onClick, disabled }) => { 2 const buttonStyle = { 3 backgroundColor: "blue", 4 color: "white", 5 padding: "10px 20px", 6 border: "none", 7 borderRadius: "5px", 8 cursor: "pointer", 9 }; 10 11 return ( 12 <button style={buttonStyle} onClick={onClick} disabled={disabled}> 13 {buttonText} 14 </button> 15 ); 16};
With the inline buttonStyle object, we’ve given our button a background color, text color, padding, and other CSS properties to improve its appearance. The 'disabled state' can be managed by adding the 'disabled' prop to the button component.
CSS-in-JS is a pattern where CSS is composed using JavaScript instead of defined in external files. One popular library for this is styled-components, which allows us to write actual CSS code to style our React components.
1import styled from 'styled-components'; 2 3const StyledButton = styled.button` 4 background-color: green; 5 color: white; 6 padding: 10px 20px; 7 border: none; 8 border-radius: 5px; 9 cursor: pointer; 10 &:hover { 11 background-color: darkgreen; 12 } 13`; 14 15export default StyledButton;
In the above snippet, we've created a StyledButton component with styled-components. This approach encapsulates the styles within the component, making it reusable and maintainable.
CSS Modules provide a way to write CSS that's scoped locally to the component, avoiding global scope and naming conflicts.
1/* Button.module.css */ 2.button { 3 background-color: red; 4 color: white; 5 padding: 10px 20px; 6 border: none; 7 border-radius: 5px; 8 cursor: pointer; 9}
1import React from 'react'; 2import styles from './Button.module.css'; 3 4const Button = ({ buttonText, onClick }) => { 5 return ( 6 <button className={styles.button} onClick={onClick}> 7 {buttonText} 8 </button> 9 ); 10}; 11 12export default Button;
By importing Button.module.css, we can use the styles object to apply our CSS classes to the React component, ensuring that the styles are not affected by other global styles.
Buttons often have different states, such as active, disabled, or loading. Let’s manage these states within our React button component.
1const Button = ({ buttonText, onClick, disabled, loading }) => { 2 const buttonStyle = { 3 // ...other styles 4 opacity: disabled || loading ? 0.5 : 1, 5 cursor: disabled || loading ? "not-allowed" : "pointer", 6 }; 7 8 return ( 9 <button style={buttonStyle} onClick={onClick} disabled={disabled}> 10 {" "} 11 {loading ? "Loading..." : buttonText}{" "} 12 </button> 13 ); 14}; 15 16// Disabled buttons use the 'pointer-events: none' property to prevent hover and active states.
Here, we’ve added logic to change the button’s opacity and cursor when it’s in a disabled or loading state. We also conditionally render the buttonText or a loading message based on the loading prop. Additionally, the 'disabled cursor' can be set to 'not-allowed' to indicate the button is inactive.
Props in React allow us to customize components. We can use props to change the button's appearance, such as its background color or size.
1const Button = ({ buttonText, onClick, color, size }) => { 2 const buttonStyle = { 3 // ...other styles 4 backgroundColor: color, 5 padding: size === 'large' ? '15px 30px' : '10px 20px', 6 }; 7 8 return ( 9 <button style={buttonStyle} onClick={onClick}> 10 {buttonText} 11 </button> 12 ); 13};
In this example, we're using the color and size props to customize the backgroundColor and padding of our button. This allows for a more dynamic and flexible button component that can be tailored to different parts of our app.
Icons can enhance the user experience by providing visual cues about the button's function. Let's integrate icons into our React buttons using an icon library.
1import { FaBeer } from 'react-icons/fa'; 2 3const IconButton = ({ onClick, label }) => { 4 return ( 5 <button onClick={onClick}> 6 <FaBeer /> 7 {label} 8 </button> 9 ); 10}; 11 12export default IconButton;
In this code snippet, we're using the react-icons library to import the FaBeer icon and render it inside our button alongside the label text.
Accessibility is crucial for all users, including those using assistive technologies. When styling buttons, we must ensure they are accessible.
1const AccessibleButton = ({ onClick, label }) => { 2 return ( 3 <button onClick={onClick} aria-label={label}> 4 {label} 5 </button> 6 ); 7}; 8 9export default AccessibleButton;
Using color or predefined button styles only provides a visual indication, which may not be conveyed to users of assistive technologies, such as screen readers. To ensure information is accessible, consider using additional attributes like aria-label or aria-describedby.
By using the aria-label attribute, we provide screen readers with a clear description of the button’s function, ensuring that all users have a good experience.
Creating responsive buttons ensures that they look great on any device. Let’s use display and gap utilities to style buttons that adapt to different screen sizes.
1/* Button.module.css */ 2.button { 3 // ...other styles 4 display: flex; 5 gap: 10px; 6 width: 100%; 7 @media (min-width: 768px) { 8 width: auto; 9 } 10} 11 12import styles from "./Button.module.css"; 13 14const ResponsiveButton = ({ buttonText, onClick }) => { 15 return ( 16 <button className={styles.button} onClick={onClick}> 17 {" "} 18 {buttonText}{" "} 19 </button> 20 ); 21}; 22 23export default ResponsiveButton;
With the help of CSS media queries and the display and gap properties, our button can adjust its width and spacing based on the screen size. You can create responsive stacks of full-width 'block buttons' using these utilities to ensure they are full-width and responsive.
Different contexts require different button variants. Let's create a primary button and a toggle button variant.
1const PrimaryButton = styled.button` 2 // ...primary button styles 3`; 4 5const ToggleButton = ({ toggled, onClick }) => { 6 const toggleStyle = { 7 // ...toggle button styles 8 backgroundColor: toggled ? 'yellow' : 'gray', 9 }; 10 11 return ( 12 <button style={toggleStyle} onClick={onClick}> 13 {toggled ? 'On' : 'Off'} 14 </button> 15 ); 16};
Here, PrimaryButton is a styled component for our primary action buttons, while ToggleButton changes its background color based on the toggled state.
Interactivity is key for engaging users. Let's add styles that change on click and hover to make our buttons more interactive.
1const InteractiveButton = styled.button` 2 // ...other styles 3 &:hover { 4 transform: scale(1.1); 5 } 6 &:active { 7 transform: scale(0.9); 8 } 9`;
This InteractiveButton component uses CSS pseudo-classes :hover and :active to create a visual feedback when the user interacts with the button.
Beyond appearance, buttons can also perform various functions. We can extend our button to act as a link or to create block and floating buttons.
1import { Link } from 'react-router-dom'; 2import styled from 'styled-components'; 3 4const ButtonLink = ({ to, label }) => { 5 return ( 6 <Link to={to} className="button-link"> 7 {label} 8 </Link> 9 ); 10}; 11 12const BlockButton = styled.button` 13 display: block; 14 width: 100%; 15 // ...other styles 16`; 17 18const FloatingButton = styled.button` 19 position: fixed; 20 bottom: 20px; 21 right: 20px; 22 // ...other styles 23`; 24 25export { ButtonLink, BlockButton, FloatingButton };
In the above examples, ButtonLink uses the Link component from react-router-dom to navigate pages, while BlockButton and FloatingButton demonstrate different layout styles for buttons. When using the <a>
element as a button, applying the disabled state can affect its functionality, as it may not be clickable in some browsers.
Performance is crucial, especially when it comes to rendering components. Let's ensure our button styles are optimized for performance.
1const MemoizedButton = React.memo(({ onClick, label }) => { 2 return ( 3 <button onClick={onClick}> 4 {label} 5 </button> 6 ); 7});
By using React.memo, we prevent unnecessary re-renders of our MemoizedButton component, which can improve the performance of our app, especially if the button is frequently updated.
When styling React buttons, it's important to follow best practices to ensure consistency and maintainability.
1const BestPracticeButton = styled.button` 2 appearance: none; 3 border: 1px solid transparent; 4 transition: background-color 0.3s ease; 5 6 &:focus { 7 outline: none; 8 border-color: blue; 9 } 10`;
This BestPracticeButton component removes the default browser styling with appearance: none, provides a smooth transition for the background color, and customizes the focus state to improve visibility without the default outline.
Even experienced developers encounter styling issues. Let's address common problems and how to resolve them.
1// Example of fixing a common issue with specificity 2const SpecificButton = styled.button` 3 && { 4 background-color: purple; 5 } 6`;
In this snippet, we've increased the specificity of our SpecificButton styles using the && syntax, which can help override styles inherited from other CSS classes.
Let's look at how React button styles are applied in real-world scenarios, such as e-commerce checkout buttons or social media share buttons.
1const CheckoutButton = styled.button` 2 // ...styles for a prominent checkout button 3`; 4 5const ShareButton = styled.button` 6 // ...styles for a social media share button 7`;
These components, CheckoutButton and ShareButton, are tailored for specific use cases in applications, demonstrating the versatility of React button styling.
To maintain consistency and efficiency, it's beneficial to export and reuse button styles across your React app.
1// SharedStyles.js 2export const commonButtonStyle = { 3 padding: '10px 20px', 4 border: 'none', 5 borderRadius: '4px', 6}; 7 8// In your component file 9import { commonButtonStyle } from './SharedStyles'; 10 11const ReusableButton = styled.button` 12 ${commonButtonStyle} 13 background-color: navy; 14`;
By exporting commonButtonStyle from SharedStyles.js, we can import and apply it to multiple button components like ReusableButton, ensuring a consistent look and feel throughout the app.
Mastering React button style involves understanding the various methods of styling, managing button states, ensuring accessibility, and applying best practices. By exploring the examples and concepts discussed in this article, you can create buttons that are not only visually appealing but also functional and accessible. Remember to keep experimenting with different styles and techniques to find what works best for your React app.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.