JSX >
JSX is like mixing HTML and JavaScript.
const element = <h1>Attack on Titan !!!</h1>
It's just JavaScript but with a slight dash of HTML.
Inside a JSX expression, attributes can be inserted very easily:
const myId = 'test'
const element = <h1 id={myId}>Hello, world!</h1>
You just need to pay attention when an attribute has a dash (-
) which is converted to camelCase syntax instead, and these 2 special cases:
class
becomesclassName
for
becomeshtmlFor
because they are reserved words in JavaScript.
Here’s a JSX snippet that wraps two components into a div
tag:
<div>
<BlogPostsList />
<Sidebar />
</div>
A tag always needs to be closed.
Transpiling JSX >
A browser cannot execute JavaScript files containing JSX code. They must be first transformed to regular JS by doing a process called transpiling.
To every JSX line, a plain JavaScript alternative is available, and that’s what JSX is transpiled to.
Here's an example comparing both the languages:
Plain JS
ReactDOM.render(
React.DOM.div(
{ id: 'test' },
React.DOM.h1(null, 'A title'),
React.DOM.p(null, 'A paragraph')
),
document.getElementById('myapp')
)
JSX
ReactDOM.render(
<div id="test">
<h1>A title</h1>
<p>A paragraph</p>
</div>,
document.getElementById('myapp')
)
See..!! How straightforward JSX is as compared to Javascript.
JS in JSX >
When writing any code in JavaScript, put them inside the curly brackets {}
.
For example, here's how to use a constant value defined somewhere:
const paragraph = 'A paragraph'
ReactDOM.render(
<div id="test">
<h1>A title</h1>
<p>{paragraph}</p>
</div>,
document.getElementById('myapp')
)
This is a basic example. Curly braces accept any JS code:
HTML in JSX >
Although JSX may resemble HTML a lot, but actually it's all XML syntax
In the end you render HTML, so you need to know a few differences between how you would define some things in HTML, and how you define them in JSX.
You need to close all tags
No more <br>
but instead use the self-closing tag: <br />
(the same goes for other tags)
camelCase is the new standard
onchange
=>onChange
onclick
=>onClick
onsubmit
=>onSubmit
class
becomes className
Because JSX is JavaScript, and class
is a reserved word, you can't write
<p class="description">
but you need to use
<p className="description">
CSS in React >
JSX Provides another way to define CSS.
the JSX style
attribute only accepts an object. This means you define properties in an object:
var divStyle = {
color: 'white'
}
ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode)
or
ReactDOM.render(<div style={{ color: 'white' }}>Hello World!</div>, mountNode)
The CSS values you write in JSX are slightly different from plain CSS:
the keys property names are camelCased
values are just strings
you separate each tuple with a comma
Is Plain CSS not required ?
CSS is an unsolved problem. Since its inception, dozens of tools around it rose and then fell. The main problem with JS is that there is no scoping and it’s easy to write CSS that is not enforced in any way, thus a “quick fix” can impact elements that should not be touched.
JSX allows components (defined in React for example) to completely encapsulate their style.
Is this the go-to solution?
Inline styles in JSX are good until you need to
write media queries
style animations
reference pseudo classes (e.g.
:hover
)reference pseudo elements (e.g.
::first-letter
)
In short, they cover the basics, but it’s not the final solution.
Forms in JSX :
JSX changes the way Forms work and thus makes is simpler for the developer.
value
and defaultValue
The value
attribute always holds the current value of the field.
The defaultValue
attribute holds the default value that was set when the field was created.
This also applies to the textarea
field, e.g.
<textarea>Some text</textarea>
but instead
<textarea defaultValue={'Some text'} />
For select
fields, instead of using
<select>
<option value="x" selected>
...
</option>
</select>
use
<select defaultValue="x">
<option value="x">...</option>
</select>
White space in JSX :
To add white space in JSX there are 2 rules:
Rule 1: Horizontal white space is trimmed to 1
If you have white space between elements in the same line, it’s all trimmed to 1 white space.
<p>Something becomes this</p>
becomes
<p>Something becomes this</p>
Rule 2: Vertical white space is eliminated
<p>
Something
becomes
this
</p>
becomes
<p>Somethingbecomesthis</p>
To fix this problem you need to explicitly add white space, by adding a space expression like this:
<p>
Something
{' '}becomes
{' '}this
</p>
or by embedding the string in a space expression:
<p>
Something
{' becomes '}
this
</p>
Adding comments in JSX :
You can just add it normally as you do in JavaScript.
<p>
{/* a comment */}
{
//another comment
}
</p>
Spread attributes :
In JSX a common operation is assigning values to attributes.
Instead of doing it manually, e.g.
<div>
<BlogPost title={data.title} date={data.date} />
</div>
you can pass
<div>
<BlogPost {...data} />
</div>
and the properties of the data
object will be used as attributes automatically, thanks to the ES6 spread operator.
How to loop in JSX :
If you have a set of elements you need to loop upon, you can create a loop and then add JSX to an array:
const elements = [] //..some array
const items = []
for (const [index, value] of elements.entries()) {
items.push(<Element key={index} />)
}
Now when rendering the JSX you can embed the items
array simply by wrapping it in curly braces:
const elements = ['one', 'two', 'three'];
const items = []
for (const [index, value] of elements.entries()) {
items.push(<li key={index}>{value}</li>)
}
return (
<div>
{items}
</div>
)
Components >
React component is the building block of a React application.
A React component represents a small chunk of user interface in a webpage. The primary job of a React component is to render its user interface and update it whenever its internal state is changed.
In addition to rendering the UI, it manages the events belongs to its user interface. React component provides below functionalities ->
Initial rendering of the user interface.
Management and handling of events.
Updating the user interface whenever the internal state is changed.
React component accomplish these features using three concepts:
Properties - Enables the component to receive input.
Events - Enable the component to manage DOM events and end-user interaction.
State - Enable the component to stay stateful. Stateful component updates its UI with respect to its state.
Types >
There are two types of components:
Class Based Components
Function Based Components
- Class Component:
Class components are like JavaScript classes. They can have more features and manage their own data (state). Here's an example:
jsxCopy codeimport React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
- Functional Component:
Functional components are like JavaScript functions. They take some input (props) and return what should be shown on the screen. Here's a simple example:
jsxCopy codeimport React from 'react';
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Welcome;
Rendering a Component >
The Syntax used for rendering/using a component is ->
<ComponentName />
Props >
As mentioned earlier, we can import the same component in different files and use it, but maybe in different files some changes in the component is needed. For that, we can use props
! Like this:
Component:
function Cat(props) {
return <h1>Meow's color is {props.color}</h1>;
}
<Cat color="purple" />
Ending >
Hope you have tried out making your own cool react app and explored it by yourself.
I hope this post has been helpful. If you have any questions, please feel free to leave a comment below.
Happy Coding !
Thank You