In this video I'll tell you what is JSX, why we are using it in React and how to add JS code inside the JSX markup.
--------------------------------
Hello, my name is Konstantyn, I'm a Frontend Engineer working in a lovely city of Warsaw. My main technology stack is React. Please ask me questions in comments and subscribe for more tutorials like this!
✅ Follow Me:
LinkedIn: / kostiantyn-burlai
Github: https://github.com/burlai
☕ Buy Me A Coffee: https://www.buymeacoffee.com/konstantyn
--------------------------------
So, JSX is a syntax which looks like HTML, but it is actually a JavaScript code. When React files are compiled to be consumed by the browser, this markup became just the pure JS code. But these are the details which should not bother you at all at the beginning of your React journey.
There are a couple of main differences between JSX and HTML if it comes to writing code:
1. Most of arguments in JSX could look differently. For example, the most used 'class' attribute from HTML will be 'className' in JSX. Or 'onclick' HTML event (all lowercase letters) will be camel case 'onClick' event in JSX. In general, almost all attributes will be in camel case.
2. We should always use closing tags in JSX, in HTML it is not always necessary.
3. When you have a code of React component, the markup should always be wrapped up in a single tag. It could be "div" or "section" tag, but it is more efficient to use "Fragment" element from React. This is a special empty tag just for this purpose. In resulting HTML there will be no any tag in place of Fragment, so we are reducing the number of tags and so called 'divitis'.
4. You can inject JS code inside JSX markup using curly braces.
For now we were writing the values of the attributes as a hardcoded values which were put inside quotes. React allows you to use JavaScript code inside JSX markup by using curly braces. It could be a variable, a function call or some if statement. Just any JS code in fact.
When we want to add an inline style to the element, we should use double curly braces.
This is because we are passing the object to the style attribute.
This feature of using JS inside JSX is very powerful, but in addition to that is very straightforward and easy to read. You just not separating your logic from your markup. This could look weird for the first time but you will pick this concept really fast with practice.
Links:
https://react.dev/learn/writing-marku...
https://react.dev/learn/javascript-in...
https://react.dev/reference/react/Fra...
#react #reactjs #reactjstutorial