Call phone number in our flutter application. This is what we are going to learn today. In this tutorial you are gonna look at a dependency called URL Launcher. This package is so powerful that will allow us to use default applications of mobile operating system in our case phone app.

For this purpose we are going to use intents of android. If you don’t know about intents. Intents are actions that are use to navigate from screen to screen of either a single application or another. There are basically two types of intents:

  • Implicit (used for calling intended actions like sharing image on different system apps)
  • explicit (communication between different activities within the same app)

So, lets start today’s tutorial.

Step 1: Installing url_launcher

You can either install it from terminal as follows:

flutter pub add url_launcher

or add in pubspec.yaml manually under dependencies

dependencies:
  url_launcher: ^6.0.20

Step 2: Add Android Dial Intent

In some case it is not required our dependency handles everything for us. When I was running on my system everything works fine without adding this intent. Yet it is important if you want to do a safe play or in case some error occurred.

Open android > app > src > main > AndroidManifest.xml file and add following code just under </application>

 <queries>
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
    </queries>

Also recommended for you: https://techluts.com/beautiful-clock-time-picker-widget-example-flutter/

Step 2: Working with main.dart

In our main file we will first need to create a field where user can enter number.

TextFormField(
      decoration: const InputDecoration(
      labelText: 'Enter Number',
      ),
      controller: numberController,
      keyboardType: TextInputType.number,
 )),

Note that I have use keyboard type of number because we don’t users to add un-necessary characters. That will effect our app and can also cause errors.

And a controller named numberController, we will use it in future to get text from input.

Now, its time to create a function that will use launch method from uri_launcher package

Future<void> _dialNumber() async {
    String phoneNumber = numberController.text.toString();
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    await launch(launchUri.toString());
  }

Lets breakdown this code, first of all everything is wrapped in an async function. Because we need to delay execution until system respond to our request. There maybe a case when there is not default app to proceed request. But that is soo minimal. Inside this function we are first getting text from controller. Next is creating a url.

For this purpose, we are using Uri(). This class is use to parse urls. For example in our case we defining components of url.

Finally, launching that url with launch() fucntion.

Last step is assigning this function to our button.

Container(
margin: const EdgeInsets.fromLTRB(10, 20, 0, 0),
child: ElevatedButton(
child: const Text('Call'),
onPressed: () => _dialNumber(),
))

Here is the final main.dart file

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: const Text("Dial Number From Flutter App"),
            ),
            body: Center(child: Dial())));
  }
}

class Dial extends StatefulWidget {
  DialScreen createState() => DialScreen();
}

class DialScreen extends State<Dial> {
  TextEditingController numberController = TextEditingController();

  Future<void> _dialNumber() async {
    String phoneNumber = numberController.text.toString();
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    await launch(launchUri.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            top: true,
            child: Center(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                      padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                      margin: const EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: TextFormField(
                        decoration: const InputDecoration(
                          labelText: 'Enter Number',
                        ),
                        controller: numberController,
                        keyboardType: TextInputType.number,
                      )),
                  Container(
                      margin: const EdgeInsets.fromLTRB(10, 20, 0, 0),
                      child: ElevatedButton(
                        child: const Text('Call'),
                        onPressed: () => _dialNumber(),
                      ))
                ],
              ),
            )));
  }
}
Dail Number From Flutter

This is it for this article. Now you are able to call phone number using default phone app and make a call in any project.

Clock time picker is we mostly use when needed to fetch time from user side. Todays article is gonna be fun, because I will show you how we can create an attractive time picker using library provided by material design itself. No extra packages needed to do this task.

Recently I was working on it as I need it for my project. I will create a step-by-step guide on how you can also implement time picker in your future projects. This tutorial is beginner friendly but you are required to have a little prior knowledge about flutter.

Before stating let me tell you what we are going to use showTimePicker function provided by material.dart package. So lets get into coding.

Step 1 – Importing material.dart

Usually in all flutter projects we import built-in material.dart package. This package contains tons of pre-made widgets that work both for Android and IOS.

import 'package:flutter/material.dart';

Step 2 – Creating Stateless Widget

Next we are going to create a stateless widget that is gonna wrap our stateful widget containing picker function

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Time Picker"),
        ),
        body: Center(child: PickerWidget()),
      ),
    );
  }
}

PickerWidget() is a custom widget that is stateful class.

Step 2 – Creating Clock Time Picker Widget

This widget will contain all the heavy lifting of time picker function. In this widget

class PickerWidget extends StatefulWidget {
  PickerWidget({Key? key}) : super(key: key);

  @override
  State<PickerWidget> createState() => _PickerWidgetState();
}

class _PickerWidgetState extends State<PickerWidget> {


  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: (){}, child: Text("Get Time"));
  }
}

We will create a async function that will wait for user to provide response.

I also recommend: Request Permissions In Flutter Using Permission Handler

Step 3 – Creating displayTimeDialog()

This is an async function. Why we need to use async function? You can read documentation. In simple words async function provide us capability to stop execution until some event happens. In our case that event is use input. So our code will stop execution until user enters time.

Future<void> displayTimeDialog() async {
    final TimeOfDay? time =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
   
  }

ShowTimerPicker() takes two arguments

  • Context (Context of page)
  • InitialTime (Default time of picker)

By using TimeOfDay.now(), we are providing current system time as initial time. time variable will get user selected time and we can use it anywhere we want. Lets just pass this function to elevated button.

ElevatedButton(onPressed: displayTimeDialog, child: Text("Get Time"));

After applying some logic our main.dart file will look like

import 'dart:async';

import 'package:flutter/material.dart';

void main(List<String> args) {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Time Picker"),
        ),
        body: Center(child: PickerWidget()),
      ),
    );
  }
}

class PickerWidget extends StatefulWidget {
  PickerWidget({Key? key}) : super(key: key);

  @override
  State<PickerWidget> createState() => _PickerWidgetState();
}

class _PickerWidgetState extends State<PickerWidget> {
  String? getuserTime;

  Future<void> displayTimeDialog() async {
    final TimeOfDay? time =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (time != null) {
      setState(() {
        getuserTime = time.format(context);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: displayTimeDialog, child: Text(getuserTime!=null ? "$getuserTime": "Get Time"));
  }
}
Beautiful Clock Time Picker Widget Example Flutter

That is how can use beautiful material design time picker in our projects. If you have any quires you can comment below.

Request permissions from operating system is always a crucial part of development. Major question is why do we need permissions?

In general when we want to use resources from system like accessing files, using device locations, looking into contacts etc.. . We need to specify our system that our application is gonna use this resource. This is good for security reasons so that any third party app don’t access our data, without our knowing. But its little teasing for programmers especially for myself because I need to write some extra lines of code.

But don’t worry as a flutter developer we have a great pool of dependencies that are really efficient and we don’t need to write anything from scratch. Those packages are much efficient and reliable to use.

Let’s see how we can simply add permission feature to our highly professional and super hi-tech mobile applications. I tried to make as simple as possible just for beginners. But for professional developers like us, we can add additional conditions and functions to make it so called industry standard look.

Step-1: Installing dependency

For this purpose we are going to use permission_handler version 9.2.0. We can use any version but keep in mind if you are watching this tutorial so late in 2050 some functions maybe deprecated or discontinued. Many people get such issues. Generally upgrading version can solve this issue.

Why are we use using this package specifically? The reason is because it is pretty stable and more than 2000 developers trust it.

We can install this package by running this in terminal:

flutter pub add permission_handler

or by adding this line under dependencies in pubspec.yaml file:

dependencies:
  permission_handler: ^9.2.0

Importing package:

import 'package:permission_handler/permission_handler.dart';

Step-2: Making requests and handling response

Now we have successfully installed our dependency. Its time to use it. For this particular example we are gonna request for storage access and we will hack all mobile data.

We can access any resource by using Permission class. For example Permission.camera, Permission.bluetooth etc..

We use

Permission.storage

Getting permission status. Whether permission is granted, denied, resticted or denied permanently.

Permission.storage.status

As we need to wait for user. Until he ask from his family and friends to allow our app for accessing storage. We are using async function and storing our status in a variable.

Future requestPermission() async {
    var result = await Permission.storage.request();
}

We can also apply logical operations by using result variable.

Future requestPermission() async {
    var result = await Permission.storage.request();

    if (result == PermissionStatus.granted) {
      print("Access Granted");

    } else if (result == PermissionStatus.denied) {
      print("Access Denied");
    } else if (result == PermissionStatus.permanentlyDenied) {
      print("Access denied permanently");
    }
    return;
  }

Now finally its time to use this function. For this purpose I have created a statefull widget and button in center screen.

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main(List<String> args) {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Center(
          child: ElevatedButton(
                  onPressed: () {},
                  child: Text("Request")),
        )),
      ),
    );
  }
}

Calling our function final code will look like this

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main(List<String> args) {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  
  Future requestPermission() async {
    var result = await Permission.storage.request();

    if (result == PermissionStatus.granted) {
      print("Access Granted");
    } else if (result == PermissionStatus.denied) {
      print("Access Denied");
    } else if (result == PermissionStatus.permanentlyDenied) {
      print("Access denied permanently");
    }
    return;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Center(
          child: ElevatedButton(
                  onPressed: () {
                    requestPermission();
                  },
                  child: Text("Request")),
        )),
      ),
    );
  }
}

We can apply some logic to do some actions when user finally agree to give us access their personal data.

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main(List<String> args) {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({Key? key}) : super(key: key);

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  bool permissionStatus = false;


  Future requestPermission() async {
    var result = await Permission.storage.request();

    if (result == PermissionStatus.granted) {
      print("Access Granted");
      setState(() {
        permissionStatus = true;
      });
    } else if (result == PermissionStatus.denied) {
      print("Access Denied");
    } else if (result == PermissionStatus.permanentlyDenied) {
      print("Access denied permanently");
    }
    return 0;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Center(
          child: permissionStatus
              ? Text("Permission Granted!")
              : ElevatedButton(
                  onPressed: () {
                    requestPermission();
                  },
                  child: Text("Request")),
        )),
      ),
    );
  }
}

Walla!!! Congratulations you are now able to get access to your user’s personal data. If you find this article helpful. Please provide your fruitful comment bellow.

These 5 advices are for beginner programmers who are in learning phase. I remember my beginning period when I was just learning to code. I was following Youtube channels ,learning through courses and online articles. But still getting too much errors. Every beginner programmer pass through a period when he / she starts thinking that he can do anything, he is the best of all or he don’t need anyone for help.

These things feels exciting and looks motivating but actually they aren’t. In my 4 years of experience in coding and development, I realized that respect is the key to knowledge and growth. If you can’t respect your seniors as well as juniors you can’t grow. In this article, I am going to share some some advices that will help you in your programming career.

1- You don’t know everything

After learning through some courses and reading some books new programmers start thinking, that they know everything. But if you look at most successful people in your life, you will notice they are always gaining knowledge.

The only true wisdom is knowing you know nothing.

SOCRATES

So, very first lesson is to never stop learning new things. Technology is evolving everyday and there is always something new to learn.

We also recommed: HTML5 in 5 minutes: Lets learn web programming.

2- Learn project base things

Another most common way beginner programmer follow is learning core concepts without any purpose. Although you should learn everything but without implementation it is useless.

Without knowledge action is useless and knowledge without action is futile.

ABU BAKAR

Most recommended way is learning less and implementing more. For example when learning Flutter (Cross Platform Mobile Application Development Framework), I often use to create small handy applications using little concepts.

Believe me, this approach is way better than watching whole course of flutter and implementing nothing.

3- Never give up

” Failure is the key to success “. We all have heard this many times, But in programming you will experience this in real-time. I remember when I was just started learning. There were errors everywhere. Error, Error & Error in each line of code. At that time it was so frustrating and many people quit there.

In programming, as in everything else, to be in error is to be reborn.

ALAN PERLIS

It means in programming career, error is just like girlfriend. Even if you don’t like it you have to face it everytime. Just joking!

Dealing with problems is most essential part of programming. You always have to keep in mind that every problem have some solution. Never give up.

Sites every beginner programmer should use in his/her daily life to find solutions:

4- Learn from senior

As I said earlier, learning should never stop. But if someone ask me about the best way of learning anything. I will highly recommend him to go and find an experienced person.

The only source of knowledge is experience.

Albert Einstein

You can find you mentor in online community sites like:

or social media sites like Facebook, Twitter, Instagram etc. Interact with people who are better in their fields, and you will automatically start growing fast.

5- Do programming with passion

The last tip is most important of all. Some people come into programming because someone had told them, they can make lots of money from it. Although programming pays more than average jobs, but doing is just for money will make you tired soon and most people quit there.

My teacher once said:

If you are doing something whole day, just because you like it. This is your passion follow it.

He meant that if you are doing something not for money, just because you are feeling good in it, then keep doing it. It will pay alot in future.

If you enjoy solving problems, taking challenges and sitting in front of computer, then programming is for you. Do it will full passion and this is gonna pay you more than your thoughts.

These are 5 tips you must follow if you are just getting into coding. You can share your thoughts in comment below.

Listview is one of the most basic and most used component in mobile application development. Almost all modern apps use lists in different forms. In this article we will take a lock at how to use a list view and how to sync it with Tabbar layout for ultimate UI experience.

Prerequisites:

  • Basic knowledge of is necessary (as this is not a flutter beginners guide).
  • Installed and setup flutter SDK.
  • In this guide we will be using VS Code.

Getting Started:

Creating our project:

To create a new project, type in cmd.

flutter create --org com.techluts tabbar_app

after creating new project. Open it in VS Code.

flutter folder hierarchy

Here you will find some files and folders that are created by default from flutter SDK.

Navigate to lib>main.dart . Remove the default boilerplate code and paste following:

import 'package:flutter/material.dart';

void main() {
  runApp(MainScreen());
}

class MainScreen extends StatefulWidget {
  MainScreen({Key? key}) : super(key: key);

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

In this code we are creating a Statefull Widget called MainScreen. This will contain tabs and listviews.

To create a tab bar layout we need to wrap Scaffold with DefaultTabController() widget class. _MainScreenState class will look like

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(appBar: AppBar(
          title: Text("TabBar App"),
          )
        ),
      ),
    );
  }
}

DefaultTabController have two required attributes:

  • length (defines how many tabs are being displayed)
  • child (Child widget wrapping tabs )

Creating Tabs:

Tabs are the most important components for us because our app will relay on them. So lets start creating tabs.

To create a tabbar on top of screen we need to use TabBar() widget class that will contain all tabs. To do so we need to use bottom attribute of AppBar class.

Scaffold(
          appBar: AppBar(
          title: Text("TabBar App"),
          bottom: const TabBar(
            tabs: [
              Tab(icon: Icon(Icons.directions_car)),
              Tab(icon: Icon(Icons.directions_transit)),
              Tab(icon: Icon(Icons.directions_bike)),
            ]
            ),
          )
        ),

As a result of this code, tabs will start showing and can circulate through them.

tabsr in flutter

To add bind screens with these tabs. We will need another class widget called TabBarView

Scaffold(
          appBar: AppBar(
          title: Text("TabBar App"),
          bottom: const TabBar(
            tabs: [
              Tab(icon: Icon(Icons.directions_car)),
              Tab(icon: Icon(Icons.directions_transit)),
              Tab(icon: Icon(Icons.directions_bike)),
            ]
            ),
          ),
          body:  const TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),

Congratulations we have successfully created our Tab bar layout, that most of modern apps use in common. Now app is looking something like:

tabs-flutter

Its time to add a ListView instead of Icons.

Adding ListView:

In place of three icons we will create three listviews with different data. We can either create them in separate files. This will help in increasing code readability and management. But for the sack of simplicity we are using only one file main.dart.

So we are going to create a reusable list widget using ListView.builder() class. This will look like following:

class ListWidget extends StatelessWidget {
  Icon ic = const Icon(Icons.abc);
  ListWidget(this.ic, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<String> list = [
      "item1",
      "item2",
      "item3",
      "item4",
      "item5",
      "item6",
      "item7",
      "item8"
    ];
    return ListView.builder(
        itemCount: list.length,
        itemBuilder: ((context, index) {
          return Card(
            child: ListTile(
              leading: ic,
              title: Text(list[index]),
            ),
          );
        }));
  }
}

Lets understand this code.

Here we are using custom widget with class name ListWidget. This widget is accepting a Icon as a parameter. Once icon is received this will be passed to ListTile() widget in Card() widget. If you are not familiar with these widgets you can view documentation of card class and ListTile class.

Finally we have completed our project and our resutlts look something like this:

ListIView + Tabs
import 'package:flutter/material.dart';

void main() {
  runApp(const MainScreen());
}

class MainScreen extends StatefulWidget {
  const MainScreen({Key? key}) : super(key: key);

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            title: const Text("TabBar App"),
            bottom: const TabBar(tabs: [
              Tab(icon: Icon(Icons.directions_car)),
              Tab(icon: Icon(Icons.directions_transit)),
              Tab(icon: Icon(Icons.directions_bike)),
            ]),
          ),
          body: TabBarView(
            children: [
              ListWidget(const Icon(Icons.directions_car)),
              ListWidget(const Icon(Icons.directions_transit)),
              ListWidget(const Icon(Icons.directions_bike)),
            ],
          ),
        ),
      ),
    );
  }
}

class ListWidget extends StatelessWidget {
  Icon ic = const Icon(Icons.abc);
  ListWidget(this.ic, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<String> list = [
      "item1",
      "item2",
      "item3",
      "item4",
      "item5",
      "item6",
      "item7",
      "item8"
    ];
    return ListView.builder(
        itemCount: list.length,
        itemBuilder: ((context, index) {
          return Card(
            child: ListTile(
              leading: ic,
              title: Text(list[index]),
            ),
          );
        }));
  }
}

Thanks for reading this article. If you have any queries let me know in the comments.

JSX maybe you know or not is used in react to develop user interfaces. it was introduced with react to help developers in writing readable and manageable code. In this article we will discuss deeply about its syntax and uses.

As we discussed earlier JSX is a web structuring technology that resembles HTML. Here main concern is why should we use JSX.

React doesn’t require JSX. We can also write react webapps without using it.

For You: HTML5 in 5 minutes: Lets learn web programming.

Why JSX?

It has many benefits in JavaScript enviroment:

  • Its easy to learn & code because syntax resembles HTML.
  • Can be use as an expression (Assign to a variable).
  • We can use it directly in JavaScript code.
  • Other elements can be added as children.

This in background is using react core library to create elements with specified attributes. This may look confusing but here we will see some examples and try to understand with and without JSX.

/*--- Hello World without jsx -----*/
React.createElement("h1", null, "Hello world!");

/*--- Hello World with jsx -----*/

<h1>Hello world!</h1>;

As we can see using it make our life easier as a frontend developer because now code is more readable and easy to write.

Its resembles HTML but keep in mind its just a JavaScript code in background. Like normal HTML5 tag we can can add attributes of elements.

<a href="https://youtube.com/">Youtube</a>

There are some differences between HTML and JSX. Lets discuss about them:

  • Each tag must end by closing tag.
  • Here each attribute can be written in camel case.
  • class and other html attributes like for are written as className and HTMLFor.
  • Inline styling can be done in the form of objects.

Here question arises why we need to use className rather than class.

Attributes in JSX:

Attributes like class, for, onclick etc contains keywords that are reserved in JavaScript programming language. For example class keyword is reserved for JavaScript classes and for keyword is used in looping. So to avoid syntax errors attributes are written in camel case without spaces.

/* ------------  HTML Form ------------------*/
<div class="form-wrapper">
  <label class="label-name" for="name">Enter your name: </label>
  <input class="input-name" type="text" id="name" />
</div>
/* ------------  HTML Form ------------------*/
 <div className="form-wrapper">
        <label className="label-name" htmlFor="name">Enter your name: </label>
        <input className="input-name" type="text" id="name" />
 </div>

To convert Html code into JSX you can visit here.

Nesting Components:

Another important feature is component nesting into other.

import React from "react";
function List() {
  return (
    <ul>
      <li>Butter</li>
      <li>Milk</li>
      <li>Cheese</li>
      <li>Yougart</li>
    </ul>
  );
}

function Label() {
  return <h1>Dairy Products:</h1>;
}

function Product() {
  return (
    <>
      <Label />
      <List />
    </>
  );
}

This feature helps in creating small units for a larger complex UI. Components are reusable and easy to manage. Embedding one component into other forms a hierarchy which forms a tree of elements. Easily manageable, scalable and reusable.

JSX and JavaScript:

As we discussed earlier it can be used directly in our code. Here is an example of loop mapping using lists.

let items = ["Butter", "Milk", "Cheese", "Yougart"];

<ul>
      {items.map((item, index) => {
        <li key={index}>{item}</li>;
      })}
</ul>

Styling Components:

Styling is most important part of designing a web application. Its helps us making webpages more user friendly and interactive. JSX has huge support in to use css element based system. We can use style attribute in each element but in different way.

Here is an example to show you some difference between both of them using inline styling methodology.

/*----- Normal CSS   -------*/

<h1 style="color:red;">Hello</h1>
/*----- Normal CSS   -------*/

<h1 style={{color:"red",}}>Hello</h1>

Here we can see, JSX being part of a programming language works in different way. We have to follow some major rules:

  • CSS attributes must be enclosed in {} brackets
  • Those attributes must be camel case.

Passing styles as an object:

Since it uses CSS attributes in the form of key-value pair. We can separate styling from structuring.

Here you can follow this example.

let headingStyles = {
	color:'red',
	backgroundColor:'black',
	fontWeight:'bold'
};


<h1 style={headingStyles}>Hello</h1>

Conclusion:

JSX is a structuring language for react. Also closely resembles HTML but is different in syntax. It makes designer life easier by creating element hierarchy tree. We can style it same as normal webpages but also need to follow some rules.

Thank you for your time. I hope you have learned something. Please let us knoe comment below if you have any queries. Have a great day!