As React continues to grow in popularity, developers are constantly seeking efficient and effective solutions for styling their applications. Meta’s solution StyleX fills this need by offering a versatile toolkit that caters to the diverse styling requirements of modern web development projects. With its focus on scalability, efficiency, and type safety.
Before we start exploring StyleX, it’s good to have some basic knowledge about React.js and how front-end development works. You should be comfortable with JavaScript, JSX (which is like HTML but for React), and how to manage packages with npm. It’s also helpful to know a bit about CSS, the language used to style websites.
To get started with StyleX in your React project, you’ll first need to install it as a dependency. You can do this using npm, the Node.js package manager. Open your terminal or command prompt and navigate to your project directory. Then, run the following command:
I decided to put together a guide to set up a React development environment with StyleX using Vite. We chose Vite for its speed and efficiency, making it an ideal choice for React projects. Below are the installation steps:
# Step 1: Create a Vite project with React
npm create vite@latest
cd vite-project
npm install
# Step 2: Install StyleX
npm install --save @stylexjs/stylex
# Step 3: Install vite-plugin-stylex
npm i vite-plugin-stylex
# Step 4: Edit vite.config.js
# Add the following line
import styleX from "vite-plugin-stylex"
export default defineConfig({
# Add styleX() to the plugins
plugins: [react(), styleX()],
})
# Step 5: Edit package.json
# Add this to your package.json.
"overrides": {
"vite-plugin-stylex": {
"@stylexjs/babel-plugin": "0.4.1"
}
}
# Step 6: Update the project
npm update
# Step 7: Run the project in dev mode
npm run dev
To utilize StyleX in our project, we import the entire module using the import statement. By using * as stylex, we import all the exports from the @stylexjs/stylex module and alias them as stylex, which allows us to access StyleX functionalities throughout our codebase.
import * as stylex from "@stylexjs/stylex";
import "./App.css";
import * as stylex from "@stylexjs/stylex";
import Button from "./Common/Button";
const styles = stylex.create({
btnContainer: {
display: "flex",
alignItems: "center",
justifyContent: "center",
},
main: {
color: "blue",
},
});
const App = () => {
return (
<>
<h1 {...stylex.props(styles.main)}>
Introduction to StyleX: Meta's Solution for Styling in React
</h1>
<div {...stylex.props(styles.btnContainer)}>
<Button btnTxt={"cick me"} variant="danger" />
<Button btnTxt={"cick me"} variant="primary" />
</div>
</>
);
};
export default App;
The code illustrates a React application that uses the StyleX library for style. It initially loads a CSS file with extra styles and the StyleX library for dynamic styling. The primary React component, App, displays a title and a container with StyleX-styled buttons. The stylex.create() function establishes the styles for the button container and the main title, allowing for more flexibility and modular design. The primary title of the App component is displayed with StyleX styles, which ensures consistent theming across the application.
A container with buttons is also shown, each with a distinct style depending on their version, exhibiting StyleX’s adaptability in handling component styling. Overall, the code demonstrates the integration of StyleX into a React application to achieve dynamic and consistency.
In our code, we have a Button component that is being utilized in the App component. We are also passing some props to the Button component. These props likely include the text to be displayed on the button (btnTxt) and the variant of the button (variant).
Now, let’s explore what’s inside the Button component and how we can utilize these props to apply conditional styling using StyleX.
import React from "react";
import * as stylex from "@stylexjs/stylex";
interface ButtonProps {
btnTxt: string,
variant?: "primary" | "danger",
isLarge?: boolean
}
const btnStyle = stylex.create({
base: {
fontSize: "20px",
padding: "10px"
},
primary: {
background: "blue"
},
danger: {
background: "red"
}
Large:{
fontSize:"3rem"
}
})
function index({ btnTxt, variant = "primary", isLarge = false}: ButtonProps) {
return (
<div>
<button {...stylex.props(btnStyle.base,btnStyle[variant], isLarge && btnStyle.large)}>
{btnTxt}
</button>
</div>
);
}
export default index;
The Button component is a functional React component that renders a button element with dynamic styling based on the supplied properties. It imports the React and StyleX libraries to manage styles. The ButtonProps interface specifies the components’ expected props, such as btnTxt for the button text and an optional variation parameter, which can be “primary” or “danger” to signal alternative button styles.
Within the component, StyleX is used to build button styles. The btnStyle object defines three styles: a basic style (base) for typical button attributes like font size and padding, and two variant styles (primary and danger) for changing background colors depending on the variation prop. We have also a conditional property large that can be controlled from props and based on that styling will applied.
The index function is the primary component function, which renders the button element. It destructures the props sent to the component, and if no variation prop is provided, it defaults to “primary”. The button element is styled conditionally using StyleX’s stylex.props() method, which applies both the base style and the relevant variant style based on the variation prop value.
Finally, the index component is exported as the default export, so it may be imported and used in other program areas.
This Button component showcases the use of StyleX for dynamic and conditional style in React components, resulting in a versatile and maintainable method for styling UI elements.
Create API: The create() method is used to define styles in StyleX. It takes an object as an argument, where each key represents a style rule and its corresponding value represents the CSS properties. This method returns a style object that can be applied to React components using the props() method.
Props API: The props() method is used to apply styles to React components. It accepts one or more style objects created using the create() method and merges them. The resulting style object can then be spread onto React components as props to apply the defined styles. This method enables dynamic and conditional styling of React components based on different criteria.
By using the create() and props() methods provided by StyleX, developers can efficiently define and apply styles to React components, facilitating the creation of dynamic and visually appealing user interfaces.
Type safety assures that only certain types of values can be set to a property, reducing accidental mistakes and increasing code dependability. In the given example, the customStyle prop is specified using the StyleXStyles type, which describes the structure of the custom styles object that may be sent.
interface ButtonProps {
btnTxt: string,
isLarge: boolean,
variant?: "primary" | "danger",
customStyle?: stylex.StyleXStyles<{ margin?: string }>
}
//styling code
.
.
.
//styling code
function index({ btnTxt, isLarge = false, variant = "primary", customStyle }: ButtonProps) {
return (
<div>
<button {...stylex.props(btnStyle.base, btnStyle[variant], isLarge && btnStyle.large, customStyle)}>{btnTxt}</button>
</div>
);
}
The customStyle attribute is required to be an object containing CSS properties, with the exception that only the margin property is permitted. If a developer attempts to assign any other style property, TypeScript will generate a compile-time error, informing the developer of the erroneous usage. This guarantees that only valid styles are supplied to the customStyle parameter, avoiding runtime problems and ensuring stylistic uniformity throughout the application.
By ensuring type safety in this way, developers can write more robust and error-free code, identifying possible issues early in the development process and increasing the overall quality and maintainability of their React apps.
In this blog, we’ve explored Meta’s solution for styling in React applications. We’ve learned about its powerful API, including the create() and props() methods, which streamline the styling process and allow for dynamic styling based on props. By integrating StyleX into React components, developers can efficiently manage styles, ensuring consistency and flexibility in their UI designs. StyleX offers an intuitive syntax and type-safe approach.
Nadeem is a front-end developer with 1.5+ years of experience. He has experience in web technologies like React.js, Redux, and UI frameworks. His expertise in building interactive and responsive web applications, creating reusable components, and writing efficient, optimized, and DRY code. He enjoys learning about new technologies.
A Deep Dive into Modern Clinical Workflows with AI Agents & CDS Hooks
Register NowThe team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork