DEV Community

miral-zymr
miral-zymr

Posted on

Day One - JSX

This is my first blog post here and as a developer and learner, I want to keep it simple. This will be a series of React Concepts that I learn throughout. For a pro, this might be something basic, but I'll make sure the newbies find it helpful. This is just a way to keep a record of my learnings and share and get better at this.

JSX

JavaScript XML, in short JSX is used to create React Elements. JSX is mainly used to make coding easier, as it uses couples the UI logic and the functional logic at one place. JSX is an alternative to React.createElement. It allows us to define the React elements using a syntax which is similar to HTML syntax.

For example,

const simpleText = "Hello World!";
const element = <h1>{ simpleText }</h1>

The first line is simple JavaScript, defining a variable, simpleText as a string. The second line is JSX, which is creating an element and we can directly render the variable element, as shown below.

ReactDOM.render(
    element,
    document.getElementById('root')
);

After compilation, JSX expressions also become JavaScript function calls and evaluate JavaScript objects. Babel compiles JSX down to React.createElement() calls. Hence, we can easily use JSX inside if...else, for loops, assign it to variables, accept it as arguments, and return it as functions.

We can use curly braces to embed JavaScript expression to an attribute. Another benefit of using JSX is, it prevents injection attacks.

JSX can be compared to the following syntax:

React.createElement(component, props, ...children)

The first part (component) determines the type of the React element.
Some key points are:

  1. Capitalized type indicates the JSX is referring to a component. React.createElement(<Foo />, document.getElementById('root');
  2. The dot-Notation can be used to refer a React component if a single module contains several react components. <MyComponents.DatePicker />
  3. React library must always be accessible and be in scope in the JSX code. import React from 'react;
  4. User-defined components must be capitalized. <Hello toWhat="World" />
  5. When you want to render a different component based on a prop, or maybe dynamically render components based on specific values or conditions, JSX type can be defined as follows:
function Story(props) {
    const SpecificStory = component[props.storyType];
    return <SpecificStory story={props.story} />;
}

These are some basics about JSX. For my next topic, I'll be covering some advanced JSX concepts and Rendering Elements.

Top comments (0)