Categories
Uncategorized

Composition in React

Composition in React allows to import components from another function while we write normal HTML is one function. It is mainly of two types:

1) Containment:

One of its example is where WelcomeDialog function has normal HTML code, while other function FancyBorder helps to add two classes ‘FancyBorder FancyBorder-blue’ to div outside this code.

A) Here is function with normal HTML code:

function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
);
}

B) Here is function which fetches props ‘color’ from FancyBorder component in WelcomeDialog() function and adds classes ‘FancyBorder FancyBorder-blue’ to a div outside FancyBorder in WelcomeDialog() function by calling (or containing) its internal code through {props.children}.

function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}

Output can be seen through ReactDOM:

ReactDOM.render(
<WelcomeDialog />,
document.getElementById('root')
);

Another example can be seen here.

2) Specialization: In this multiple functions specializes in different works. 

Here is an example, similar to above program:

A) First there is function which creates border: 

function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}

B) Here is function which provides overall HTML structure: 

function Dialog(props) {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
{props.title}
</h1>
<p className="Dialog-message">
{props.message}
</p>
</FancyBorder>
);
}

C) Here is function which uses above two functions and adds title & message text: 

function WelcomeDialog() {
return (
<Dialog
title="Welcome"
message="Thank you for visiting our spacecraft!" />
);
}

D) Here is output generated: 

ReactDOM.render(
<WelcomeDialog />,
document.getElementById('root')
);

Here is another program example of specialization.

Categories
Uncategorized

Lifting State Up in React.JS

Many times we want to reflect a change somewhere, if some change done. For example, if value is less than 100, display some text otherwise, if value is greater than 100, then display different text. It has been shown in following program:

1) First create a class of React. First of all it creates a constructor(), which includes initial state (this.state) of temperature to empty. And an event binding has been done for handleChange. In next, handleChange event has been coded to change the initial empty state of temperature to an value (e.target.value) which is entered by user. Finally, in this class, in render(), HTML coding has been done, for creating a fieldset, where onChange in any text in this field, handleChange() event made before will fetch the latest value entered. Same value written by user has been assigned to fieldset’s ‘value’ which is ‘this.state.temperature’. Inside fieldset, we have created a function ‘BoilingVerdict’ whose props ‘celsius’ has value of ‘temperature’ entered by user:

class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {temperature: ''};                                             

this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.setState({temperature: e.target.value});
}

render() {
const temperature = this.state.temperature;
return (
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input
value={temperature}
onChange={this.handleChange} />
<BoilingVerdict
celsius={parseFloat(temperature)} />
</fieldset>
);
}
}

2) BoilingVerdict function called in class above has been created below. What it does is, it fetch the value of props which is stored in ‘celsius’. If the value of ‘celsius’, entered by user, for temperature is more than 100, then return a message written in HTML, otherwise return other message written in HTML, in this function.

function BoilingVerdict(props) {
if (props.celsius >= 100) {
return <p>The water would boil.</p>;
}
return <p>The water would not boil.</p>;
}

3) In the end the class ‘Calculator’ output has been displayed in ReactDOM.

ReactDOM.render(
<Calculator />,
document.getElementById('root')
);

What it do is, if user enter a number less than 100, it shows message: The water would not boil.

If the user entered a number greater than or equal to 100, then it shows message: The water would boil.


This get more complex with new conditions added. For example, if we want to show temperature automatically changed from Celsius to Fahrenheit and vice-versa in two text boxes and also show a message if temperature is less than 100 Degree Celsius or more than it, then such a example can be seen here.

Categories
Uncategorized

Forms in React.JS

To create class in React, it take the same pattern of creating class,  functions, render () and display output through ReactDOM. 

1) Text box: Here are the steps to create a simple form with a textbox: 

A) First of all create a class, and put a constructor function in it. Constructor function contains this.state which contains initial value as empty. After that it includes two bind for handleChange() function and handleSubmit() function. It has been shown below: 

class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

B) Secondly handleChange() function has been created which sets the value of newly written text. handleChange() runs on every button pressed and displayed value updates as user press any button. And handleSubmit() function displays message that ‘A name was submitted: name’. this.state.value displays the value entered.

handleChange(event) {
this.setState({value: event.target.value});
}

handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}

C) Render() has the actual code for form which shows onSubmit of form handleSubmit() function should run. After that there is HTML form with input type of text (textbox) which has value of text entered and onChange of this value handleChange() function is called. Finally there is submit button, when this button is clicked, onSubmit event defined in <form> gets called.

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}

D) ReactDOM renders the class output.

ReactDOM.render(
<NameForm />,
document.getElementById('root')
);

2) Textarea: Textarea has similar React code as textbox. In above code all we need to do is replace replace HTML part of textbox syntax to textarea syntax inside render(), which make it:

<textarea value={this.state.value} onChange={this.handleChange} />

3) Dropdown: Similarly, dropdown has similar code in React. All we need to do is replace one HTML line of textarea with following HTML code of dropdown:

<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>

and in constructor set which value to display in dropdown with this code:

this.state = {value: 'coconut'};


Adding multiple form fields: To add multiple form components at once, it handled by adding ‘name’ to each component. Let us make a checkbox and number field. 

First a class has been made, in constructor, initial checkbox value is set to ‘true’ and initial number field value is set to ‘2’ through the names given to them:

class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};

this.handleInputChange = this.handleInputChange.bind(this);
}

handleInputChange() event has been created. In it, if target.type is checkbox, then value is 'checkbox', else value is whatever written in number field. And this value is set in 'this.setState'. 

handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;

this.setState({
[name]: value
});
}

After that an actual form has been created in render(). First a checkbox has been created with name ‘isGoing’, later a number field has been created with name ‘numberOfGuests’. 

render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}

Finally the values has been rendered using ReactDOM:

ReactDOM.render(
<Reservation />,
document.getElementById('root')
);


If you want to set more validations in React, then another alternate is a https://formik.org/

Categories
Uncategorized

List and Keys in React.JS

Convert array to list: Let us convert array to list in React.JS. 

1) First we have a const array element named arr_numbers. 

const arr_numbers = [1, 2, 3, 4, 5];

2) This array will be fetched by ReactDOM and assigned value numbers: 

ReactDOM.render(
<NumberList numbers = {arr_numbers}/>,
document.getElementById('root')
);

3) While the ReactDOM get array, a function NumberList() will be made to get this props so that it can be put in list structure, and finally it will be returned to reactDOM: 

function NumberList(props){
const list = props.numbers;
const listItems = list.map(
(number) => <li key={number.toString()}>
{number}
</li>
);
return (
<ul>{listItems}</ul>
);
}

It is a javascript method to convert to convert array to list: list.map((number) => <li> {number} </li> and it has been used in NumberList(props) function. Keys help react identify values changed in array, so ‘key’ has been assigned value of number, after converting it to string form. 


If we use keys in arrays, they should be unique among their siblings. It help to use them all at once with common code. For example, we have keys:  id, title and contents in following array: 

const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
];

In ReactDOM, we fetch value of this array in property posts: 

ReactDOM.render(
<Blog posts={posts} />,
document.getElementById('root')
);

Now we can create a function Blog() with which fetch its property posts: 

function Blog(props) {
const content = props.posts.map((post) =>
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{content}
</div>
);
}

We created a constant ‘content’ in function and mapped props value of posts. We fetched id, title and content as {post.id} assigned as React key, {post.title} and {post.content} and put it in html structure to display all content of array by return() in function and the function gets rendered in ReactDOM.


Map() in JSX: JSX allows to embed any expression in curly braces. So we could use map function directly in return() inside curly braces as 

{list.map(
(number) => <li key={number.toString()}>
{number}
</li>
)}

Rest of the code is similar to first example of this page. Overall code is: 

const arr_numbers = [1, 2, 3, 4, 5];

ReactDOM.render(
<NumberList numbers = {arr_numbers}/>,
document.getElementById('root')
);

function NumberList(props){
const list = props.numbers;

return (
<ul>
{list.map(
(number) => <li key={number.toString()}>
{number}
</li>
)}
</ul>
);
}

Categories
Uncategorized

Conditional rendering in React.JS

Conditional rendering in React.JS is done after encapsulating all components and then render them using if, else statements. Here is a simple example: 

If user is logged in, render, ‘Welcome back!’ else render, ‘Please sign up!’. We create two functions for it first:

function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}

Now let us create a function which checks if ‘isLoggedIn’ value is ‘true’ then it render ‘UserGreeting(props)’ function, else it render ‘GuestGreeting(props)’ function: 

function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}

In end we render the Greeting(props) function and we can set true and false value for isLoggedIn to true or false in ReactDOM as follows: 

ReactDOM.render(
// Try changing to isLoggedIn={true}:
<Greeting isLoggedIn={false} />,
document.getElementById('root')
);


Now let us display login and logout button with message. It can be done with following code: 

1) First we add above mentioned code:

function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}

function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}

2) Then we create login button function:

function LoginButton(props) {
return (
<button onClick={props.onClick}>
Login
</button>
);
}

3) Then we create logout button function:

function LogoutButton(props) {
return (
<button onClick={props.onClick}>
Logout
</button>
);
}

4) Then we create class ‘LoginControl’.

A) It has constructor function which do button click bindings and set initial state of ‘isLoggedin’ to false.

class LoginControl extends React.Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn: false};
}

B) Then we create handleLoginClick() function which sets the isLoggedin state to ‘true’.

handleLoginClick() {
this.setState({isLoggedIn: true});
}

C) Similarly we create function, handleLogoutClick() function which sets the isLoggedIn state to ‘false’, when called.

handleLogoutClick() {
this.setState({isLoggedIn: false});
}

D) In render we create buttons and set conditions on them. If it is logged in, then display ‘Logout’ button, else display ‘Login’ button. Then we call ‘Greeting’ function which display messages.

render() {
const isLoggedIn = this.state.isLoggedIn;
let button;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}

return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}

5) When ‘LoginControl’ class is rendered in ReactDOM, initial state of isLoggedIn is set to false in constructor.

ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);


AND Operator (&&): If condition of left of && is ‘true’ then it display element on right of &&, otherwise it skip it. Let us see example: 

1) First we create a function mailbox(). It fetches unreadMessages array from ReactDOM. In return(), we count the array length using unreadMessages.length. If the length is more than 0, then display length value with message:

function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}

2) ReactDOM is fetching unreadMessages from an array named ‘messages’, as shown below:

const messages = ['React', 'Re: React', 'Re:Re: React', 'hi'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);

 

Categories
Uncategorized

Handling events in React.JS

Event handling in React is slightly different from Javascript.

1) In Javascript, we write:

<button onclick="activateLasers()">
Activate Lasers
</button> 

however in React, we write: 

<button onClick={activateLasers}>
Activate Lasers
</button>

2) In React, we can not return false, it can be done by calling ‘PreventDefault’ explicitly. In javascript: 

<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>

In react, we use ‘PreventDefault’:

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}

return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}


The reason developers use React.JS is that it allows to break javascript functions to a deeper level for making complex functionalities, rather than making changes in overall structure of project. Jquery has a simple Toggle function(), same functionality can be added through Javascript using if and else conditions. Let us see how to create toggle functionality in React.JS:

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}

ReactDOM.render(
<Toggle />,
document.getElementById('root')
);

First of all an ES6 class named ‘Toggle’ has been created. It contains constructor() function, handleClick() function and render() function. Finally this class has been rendered using ReactDOM.render(). Let us know about them one by one:

1) constructor() function, is used to initialize local state of the component through this.state object. A constructor function also binds event handler methods that occur in component. 

So this makes it clear that the initial state of function has been set to true through:

this.state = {isToggleOn: true};

In Javascript, methods are bound by default. In React, it need to be bound manually. If we miss binding here, then, when we call function on button like onClick={this.handleClick}, then it will be undefined. So to bind it, we write following code: 

this.handleClick = this.handleClick.bind(this);

(Various binding methods has been explained in end of this page.)

2) The handleClick() function uses this.setState which is only way to update initial state. The !prevState.isToggleOn is opposite of isToggleOn, ( ! = opposite ) so it sets isToggleOn to false. So we used it as shown below:

handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

 3) In the end we used the render() function which holds the visible part of the button. It is a simple button coding in HTML <button> ON </button> , inside it, it holds ternary operator of javascript, which says if this.state.isToggleOn is true, then show ‘ON’ text, else show ‘OFF’ text. It also holds another javascript function ‘onclick()’ which calls function handleClick() in a react way onClick={this.handleClick}. All this combined makes following code: 

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}

Whole of the above code in ‘toggle’ class gets rendered through ReactDOM.render() as shown below:

ReactDOM.render(
<Toggle />,
document.getElementById('root')
);


Binding done above in constructor() function above through code. It is one method of binding:

this.handleClick = this.handleClick.bind(this);

Binding can be done in various ways. Let us study them one by one:

1) We can remove above binding code and write the handleClick() function in following way:

handleClick = () => {

Overall handleClick() function will look like: 

handleClick =() => {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

2) Another method is if we use e and arrow key in render() function directly onClick={(e)=>this.handleClick(e)} , like:

render() {
return (
<button onClick={(e)=>this.handleClick(e)}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}

3) Another method is if we write ‘bind’ and ‘this’ onClick={this.handleClick.bind(this)} in render() function directly. Overall render() function code look like:

render() {
return (
<button onClick={this.handleClick.bind(this)}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}


If we have a row ‘id’ as well, then we can write binding method as:

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Both of the above two button codes for binding give correct output.

Categories
Uncategorized

State & Lifecycle in React.JS

Lets create a simple clock function to do encapsulation of clock function:

function Clock(props) {
return ( <h1> Date is {props.date.toLocaleTimeString()}.</h1> );
}

This function will fetch value from component Clock, which we will define directly while rendering output:

function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}

In the end we add ‘setInterval’ function:

setInterval(tick, 1000);


Converting function to class: In above, ‘Clock()’ itself is not a fully functional in itself, half of its code is linked in tick() function. To work on it first lets convert above Clock() function into ES6 class form. It can be done in following way:

  1. Create an ES6 class, with the same name, that extends React.Component.
  2. Add a single empty method to it called render().
  3. Move the body of the function into the render() method.
  4. Replace props with this.props in the render() body.
  5. Delete the remaining empty function declaration.

It has been shown below:

class Clock extends React.Component {
render(){
return ( <h1> Date is {this.props.date.toLocaleTimeString()}.</h1> );
}
}

Rest of the code remains same. This code can be replaced with ‘Clock(props)’ function above to make it work. 


Adding local state to a class: This can be done is three steps.

1) Create a constructor function inside class and add this code to it: 

constructor(props) {
super(props);
this.state = {date: new Date()};
}

2) Replace ‘props’ in render function with ‘state’: 

render(){
return ( <h1> Date is {this.state.date.toLocaleTimeString()}.</h1> );
}

3) Remove the Date prop from render function: 

function tick() {
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
}

It will make the overall code to look like this:

class Clock extends React.Component {

constructor(props) {
super(props);
this.state = {date: new Date()};
}

render(){
return ( <h1> Date is {this.state.date.toLocaleTimeString()}.</h1> );
}
}

function tick() {
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
}

setInterval(tick, 1000);

In above changes most of the code is in class ‘Clock’ and render function is just calling this whole class. 


Adding Lifecycle method to a Class: In above code changes done so far, reactDOM.Render is still inside tick() function. So this auto-refresh functionality should be added to class ‘Clock’ itself, so that when this class is not getting used, it do not put load on DOM. 

To set up a timer only when Clock class is called, it is known as ‘mounting’ and when the Clock is removed, timer should be cleared, it is know as ‘unmounting’ in React. This can be done by adding three functions in class.

1) First add function componentDidMount() and add following code in it: 

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

2) Then add function Unmount function componentWillUnmount() to clear timer, as follows:

componentWillUnmount() {
clearInterval(this.timerID);
}

3) After that create a tick function, to set state on date variable: 

tick() {
this.setState({
date: new Date()
});
}

Finally, we can remove the tick function from reactDOM and remove setInterval() function:

ReactDOM.render(
<Clock />,
document.getElementById('root')
);

Overall code looks like this: 

class Clock extends React.Component {

constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}

render(){
return ( <h1> Date is {this.state.date.toLocaleTimeString()}.</h1> );
}
}

ReactDOM.render(
<Clock />,
document.getElementById('root')
);


Let us take code to next level and create multiple independent clocks with above made class. For it let us make a function named App, outside this class:

function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}

And in ReactDOM, render the App() function: 

ReactDOM.render(
<App />,
document.getElementById('root')
);

Now the code is ready and encapsulated. It is not accessible to any outside component. It is accessible to only components that owns or sets it. 


Additionally, a component may choose to pass its state as ‘props’ down to its children component. To test it, let us replace {this.state.date.toLocaleTimeString()} inside render function with following code: 

render(){
return ( <h1> Current time <FormattedDate date={this.state.date} /></h1> );
}

Now we have a ‘FormattedDate’ component and it can be manipulated by creating a function for it outside class, like shown here:

function FormattedDate(props) {
return <h5> is {props.date.toLocaleTimeString()}.</h5>;
}

It makes the overall code to like: 

function FormattedDate(props) {
return <h5> is {props.date.toLocaleTimeString()}.</h5>;
}

class Clock extends React.Component {

constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}

render(){
return ( <h1> Current time <FormattedDate date={this.state.date} /></h1> );
}
}

function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}

ReactDOM.render(
<App />,
document.getElementById('root')
);

 

Categories
Uncategorized

Properties & Components in React.JS

Elements can represent user defined components with properties (props), which can be passed to a function. ‘props’ are read-only. A component can be any particular thing. Let us see example below: 

const element = <Welcome class="New" />

Here we created a component ‘Welcome’ whose property value is ‘New’. Remember to use first letter capital for function or component name (React.JS is case-sensitive language). Now we will use this property in function using component name ‘Welcome’ and ‘props’: 

function Welcome(props){
return <h1> Its, {props.class}. </h1>;
}

In the end, we render the element: 

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

It shows output:

Its, New.


We can create a function App, which has many Welcome components with different properties. For example:

function App(){
return (
<div>
<Welcome class = "This is" />
<Welcome class = "Its" />
</div>
)
}

Now let us use these components’ properties dynamically once in another function:

function Welcome(props) {
return <h1> {props.class} New. </h1>;
}

Now render the output:

ReactDOM.render(
<App />,
document.getElementById('root')
);

Its creates output:

This is New.

Its New.


Extracting components: We can create multiple components in the form of JavaScript variables however they need to be extracted during rendering, so that extracted values can be seen in structure. Let us create JavaScript variables first:

const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'https://placekitten.com/g/64/64',
},
};

We can modify the date variable value to fetch date similar to a user’s time zone:

function formatDate(date) {
return date.toLocaleDateString();
}

Now let us create a function to create overall structure of output:

function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img
className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

Props variables used above can’t show output until we extract them as shown below, while rendering output:

ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author}
/>,
document.getElementById('root')
);

Extracted variables in above shows that these should be fetched from a function whose name is ‘comment’ (starting with small ‘c’) and put them in function ‘Comment’ (starting with capital ‘c’).


 

Categories
Uncategorized

JSX in ReactJS

JSX is mixture of HTML and Javascript with new rules. For example:

const element = <h1>Hello, world!</h1>;

In ReactJS, we can use of mixture of HTML5, CSS, Javascript and JSX. It has been shown in following example: 

const name = 'Josh Perez';
const element = <h1>Hello, {name}</h1>;

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

First we create a constant (‘const’ refer to constant value) named ‘name’ and assigned to it string value. In second line, we created a JSX constant ‘element’ and assigned to it HTML + Javascript constant value {name}. Later we rendered the value of variable ‘element’ using ReactDOM. 


One JSX constant can store multiple values, such as:

const user = {
firstName: 'Harper',
lastName: 'Perez'
};

These values can be called in a function such as:

function name(user){
     return user.firstName + ' ' + user.lastName;
}

We can call this function in another constant:

const output = <h1> Hello {name(user)} </h1>;

In the end we can show this constant ‘output’ using ReactDOM: 

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


Now we can also put if, else conditions in the code using Javascript method: 

const user = '';

function name(user){
     if(user){
          return user.firstName + ' ' + user.lastName;
     }
     else {
          return 'stranger';
     }
}

Here user is empty, so it will return string ‘stranger’ in place of username. This code can be replaced in above example, to make it work. 


In react, we usually mix HTML5 and Javascript like:

const element = (
<h1 className="greeting">
Hello, world!
</h1>
);

However in ES6 method, this can be written as: 

const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);

it gives exactly same output. 

Categories
Uncategorized

Simple React example

Here is a simple React example: 

ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);

React creates a virtual DOM in memory, render outputs anything mentioned in brackets while it gets display in the HTML element whose id is ‘root’.

As we are coding in a .js file, so we can directly add javascript code in it. 


Whatever is rendered in reactJS, it can not be or updated changed. However to update it, there is need to make a new element or use inbuilt functions and pass it to ReactDOM. In example below, we are showing how to dynamically change rendered elements through javascript inbuilt function ‘setInternval’:

function tick(){

const time = (
<div>
<h1> Hello, </h1>
<h2> Time is {new Date().toLocaleTimeString()} </h2>
</div>
);
ReactDOM.render( time, document.getElementById('root') );
}

setInterval (tick, 1000);

It shows the time seconds changing in real-time. When ‘setInterval’ call the function again and again after every one second, in React it updates only time which gets changed, while rest remains same.