JSX is a popular syntax extension for JavaScript widely used with React. It enables developers to write HTML-like code in JavaScript, leading to more readable and easy-to-write code. This guide will help you set up a React project that uses JSX on a macOS system.
What is JSX?
JSX, or JavaScript XML, allows developers to write HTML within React. This makes it easier to create and add HTML elements in React components.
With JSX, you can add HTML to JavaScript, write JavaScript inside HTML, and create components that integrate seamlessly. JSX also allows for JavaScript expressions to be embedded directly into it by wrapping the expression in curly braces {}
.
Setting up a new React project
Before you start, you should have Node.js installed on your system. Node.js allows you to run JavaScript outside of a browser and comes bundled with npm (Node Package Manager), which is used to manage Node.js packages. Download Node.js from their official website.
Using npx
- To create a new React app, open your terminal and navigate to the directory where you want to create your app. Then run this command:
npx create-react-app my-app
This command creates a new React application named “my-app”.
- To start the application, you need to navigate into your new project’s directory and start the development server:
cd my-app
npm start
Your React application will now run on http://localhost:3000
.
Using yarn
If you prefer to use yarn (another popular JavaScript package manager), you can follow these steps:
- First, install yarn on your system. You can do this using the Homebrew package manager:
brew install yarn
- Then create a new React app:
yarn create react-app my-app
- Navigate into your new project’s directory and start the server:
cd my-app
yarn start
Your React application will now run on http://localhost:3000
.
Including JSX in your React project
Once you’ve created your React project, it’s ready to use JSX!
All JavaScript files that use JSX should have a .jsx
extension. This is not a requirement but is a common practice, making it clear which files use JSX.
Here’s an example of how you can use JSX in a React component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Here, the render
method returns JSX code, which looks like HTML but is actually JavaScript.
Now you’re all set up to build your own React applications using JSX on your macOS system!
Want to Learn More?
Refer to Our Beginners Guide to REACT.