Categories
React

React – Render String with HTML tags as HTML

TRY IT LIVE

Click the button below to see a live example of this example that you can edit and try for yourself.

CODE SANDBOX

There are often times when you have a string with some HTML tags such as strong that you want to render as HTML on the DOM. Most solutions online recommend using dangerouslySetInnerHTML but that is dangerous as the name suggests. The proper way to render HTML from string is to use FormattedMessage from the formatjs library (react-intl version 5).

Here is a code example:

import React from "react";
import "./styles.css";
import { IntlProvider, FormattedMessage } from "react-intl";

export default function App() {
  return (
    <IntlProvider>
      <div className="App" style={{fontSize: 24}}>
        <FormattedMessage
          id="app.greeting"
          description="Bold text example"
          defaultMessage="Look here, I can include HTML tags in plain string and render them as HTML: <b>Bold</b>, <i>Italics</i> and <a>links too</a>."
          values={{
            b: (chunks) => <b>{chunks}</b>,
            i: (chunks) => <i>{chunks}</i>,
            a: (chunks) => (
              <a class="external_link" target="_blank" href="https://jiga.dev/">
                {chunks}
              </a>
            )
          }}
        />
      </div>
    </IntlProvider>
  );
}

This should show an output as:

Play with code sample in this link: https://codesandbox.io/s/react-render-html-from-props-string-c9ogm

You can also pass the defaultMessage and values as prop values from other components.

In the above example, I have used the version 5 from the react-intl library. In the previous versions, the API is a little different. Follow the official documentation for more options such as using child elements.

Categories
jQuery Web Development

jQuery DataTable: Sorting dynamic data

Try this code sample online!

Code samples for the this post is available in GitHub and can be previewed live using the link below.

TRY LIVE

jQuery DataTable is a powerful library to super charge your HTML tables. By default DataTable can sort your data based on the content of the cells. But if you are loading your table data dynamically and want to apply a custom sorting based on the DOM data, you can use DataTable’s custom sorting code:

function applyDomBasedSorting() {
    $.fn.dataTable.ext.order['data-sort'] = function(settings, col) {
        return this.api().column(col, {
            order: 'index'
        }).nodes().map(function(td, i) {
            return $(td).attr('data-sort');
        });
    }
}

data-sort could be anything. You can define your own sorting logic here. In this example, I would like to sort name by their second names. I’m setting this value into the data-sort attribute of the td cells.

Once you have defined your custom sorting logic like above, then you can use that when initializing your data table.

applyDomBasedSorting();
$('#employees').DataTable(
      {
        "columnDefs": [
          { "orderDataType": "data-sort", "targets": [1]}
        ],
      }
  );

GitHub Source code link: https://github.com/jiga-eng/jquery-code-samples/tree/master/datatable-code-samples/sorting

Categories
HTML

First look at HTML

HTML is used to feed the content on the web page or web application.

HTML = content.

HTML is not used for styling the page if you want to style then you need to use CSS.

HTML ≠ style. CSS = style.

HTML Document Structure

All HTML document must start with <html> and end with </html>.

<body> … </body> body tag is where the content is entered and visible in the browser.

<!DOCTYPE HTML>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

If you don’t know how to run this code you can use this link and follow the steps.

HTML Headings :

  • <h1> </h1> tags are used to define the headings.
  • heading tags vary from <h1> to <h6>.
  • <h1> with the larger size and the size reduce when the number increases till <h6>.
<html>
<body>

<h1> This is h1 element </h1>
<h2> This is h2 element </h2>
<h3> This is h3 element </h3>
<h4> This is h4 element </h4>
<h5> This is h5 element </h5>
<h6> This is h6 element </h6>

</body>
</html>

you can copy paste this code and run it using editor.

HTML Paragraph:

<p> tags are used to define the HTML paragraph.

<html>
<body>

<p> This is an paragraph </p>
<p> this is an second paragraph </p>

</body>
</html>

you can copy paste this code and run it using editor.

Categories
HTML Web Development

How to run an HTML file?

Many modern editors are available to create and modify web pages. But we recommend using simple editors like Notepad (windows) and Textedit (Mac).

How to open Notepad in windows?

Open start and type notepad at search.

(OR)

Open Start > Programs > Accessories > Notepad.

How to open Textedit in Mac?

press command + space enter Spotlight search will appear and type Textedit in that search.

(OR)

Open Finder > Applications > TextEdit

For mac, we recommend installing sublime text https://www.sublimetext.com/3

Let’s get started!

<html>
<header><title> This is title </title> 
</header>
<body>
Hello world
</body>
</html>

Copy the above code and past it the Notepad (or) Textedit.

Select File > Save as

Name the file as index.html. all HTML files should be in <filename>.html format.

Double click on the file, or right-click – and choose “Open with” and select your preferred browser.

the output may look like this.

Categories
React

React: How to use Apollo with ‘Union Types’ in GraphQL

Apollo is one of the most popular React library to work with GraphQL APIs. However they don’t have native support when your APIs contain union types.

Let’s look at an example API that contains union types and how we can work with them using Apollo. Assuming you have an API like this:

{
  search(text: "an") {
    __typename
    ... on Human {
      name
      height
    }
    ... on Droid {
      name
      primaryFunction
    }
    ... on Starship {
      name
      length
    }
  }
}

that returns this response….

{
  "data": {
    "search": [
      {
        "__typename": "Human",
        "name": "Han Solo",
        "height": 1.8
      },
      {
        "__typename": "Human",
        "name": "Leia Organa",
        "height": 1.5
      },
      {
        "__typename": "Starship",
        "name": "TIE Advanced x1",
        "length": 9.2
      }
    ]
  }
}

If you use the above query via Apollo, you will see this warning messages in the browser console:

You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types. Apollo Client will not be able to accurately map fragments. To make this error go away, use the `IntrospectionFragmentMatcher` as described in the docs: https://www.apollographql.com/docs/react/advanced/fragments.html#fragment-matcher

This is because Apollo by default uses a simple heuristics matching to match the response string into the Response object. We need to do some extra work to tell Apollo how to parse the response with union types.

Apollo has a separate section on their docs about this.

Step 1: Save the information about the fragment types in a separate file:

const fetch = require('node-fetch');
const fs = require('fs');

fetch(`${YOUR_API_HOST}/graphql`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    variables: {},
    query: `
      {
        __schema {
          types {
            kind
            name
            possibleTypes {
              name
            }
          }
        }
      }
    `,
  }),
})
  .then(result => result.json())
  .then(result => {
    // here we're filtering out any type information unrelated to unions or interfaces
    const filteredData = result.data.__schema.types.filter(
      type => type.possibleTypes !== null,
    );
    result.data.__schema.types = filteredData;
    fs.writeFile('./fragmentTypes.json', JSON.stringify(result.data), err => {
      if (err) {
        console.error('Error writing fragmentTypes file', err);
      } else {
        console.log('Fragment types successfully extracted!');
      }
    });
  });

The JSON file should look something like this:

{
  "__schema": {
    "types": [
      {
        "kind": "UNION",
        "name": "UnionSearchDetails",
        "possibleTypes": [
          {
            "name": "Human"
          },
          {
            "name": "Droid"
          },
          {
            "name": "Starship"
          }
        ]
      }
    ]
  }
}

Step 2: Create fragmentMatcher using the JSON file from the previous step:

import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import introspectionQueryResultData from './fragmentTypes.json';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData
});

Step 3: Now include this fragmentMatcher in cache object and pass it to the Apollo client:

import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';

// add fragmentMatcher code from step 2 here

const cache = new InMemoryCache({ fragmentMatcher });

const client = new ApolloClient({
  cache,
  link: new HttpLink(),
});

Now all done. The warnings and errors that you noticed previously should have gone away and the Response object from Apollo should contain the correct data.

How to use ‘Union types’ in tests and storybooks?

Now that you have fixed the problem for production code, how can we fix it for your tests or storybooks?

Apollo provides MockedProvider for this purpose. Here is a sample:

<MockedProvider mocks={mocks} addTypename cache={cache}>
     <MyComponenent />
</MockedProvider>

The important change here from the sample code is that addTypename has to be true, to allow Apollo to use the __typename in the response to map the object to the correct type.

Categories
Web Development

How to become a web developer

Everyone who wants to become a web developer must know basic HTML, CSS, and Javascript. Our posts will help you to learn Web development from Beginners to Master Level. No prior knowledge required.

  • HTML is the skeleton of the webpage.
  • CSS is the muscle and skin that covers the skeleton and makes it beautiful.
  • Javascript gives the life to the whole system.

TIPS TO LEARN FAST :

  1. Get your hands dirty which conveys that you should start practicing. It is very easy to start your web development. You just need a notepad for writing the code and any browser to run it.
  2. Don’t memorize the code, just understand the usage of the elements in HTML, CSS, and JS (Javascript). It will make you a good developer.

What to do now ?

  • To become a web developer you must master the HTML (Hypertext markup language) first. HTML is the integration of several tags that should be learned first.
  • Second, comes the CSS (cascading style sheet) through which we can change the appearance of the webpage like changing the colors, size, fonts, etc…
  • Javascript is used to write functions to the web page, like testing if the entered email is valid or not while logging into some social media web sites.

In next post we will run our first webpage