1. ভূমিকা
লিট কি?
Lit হল একটি সহজ লাইব্রেরি যা দ্রুত, হালকা ওজনের ওয়েব উপাদান তৈরি করে যা যেকোনো কাঠামোর মধ্যে কাজ করে, অথবা কোনও কাঠামো ছাড়াই। Lit এর সাহায্যে আপনি ভাগ করে নেওয়ার যোগ্য উপাদান, অ্যাপ্লিকেশন, ডিজাইন সিস্টেম এবং আরও অনেক কিছু তৈরি করতে পারেন।
তুমি কি শিখবে
কিভাবে বেশ কিছু React ধারণা Lit তে অনুবাদ করবেন, যেমন:
- জেএসএক্স এবং টেমপ্লেটিং
- উপাদান এবং প্রপস
- অবস্থা ও জীবনচক্র
- হুকস
- শিশুরা
- রেফারেন্স
- মধ্যস্থতাকারী অবস্থা
তুমি কী তৈরি করবে
এই কোডল্যাবের শেষে, React কম্পোনেন্ট ধারণাগুলিকে তাদের Lit অ্যানালগে রূপান্তর করতে সক্ষম হবে।
তোমার যা লাগবে
- Chrome, Safari, Firefox, অথবা Edge এর সর্বশেষ সংস্করণ।
- HTML, CSS, JavaScript এবং Chrome DevTools সম্পর্কে জ্ঞান।
- প্রতিক্রিয়া সম্পর্কে জ্ঞান
- (অ্যাডভান্সড) আপনি যদি সেরা ডেভেলপমেন্ট অভিজ্ঞতা চান তবে VS Code ডাউনলোড করুন। VS Code এবং NPM এর জন্য আপনার lit-plugin এরও প্রয়োজন হবে।
2. লিট বনাম রিঅ্যাক্ট
লিটের মূল ধারণা এবং ক্ষমতা অনেক দিক থেকেই রিঅ্যাক্টের মতো, তবে লিটের কিছু মূল পার্থক্য এবং পার্থক্যকারীও রয়েছে:
এটা ছোট।
লিট ছোট: এটি React + ReactDOM এর 40+ kb এর তুলনায় প্রায় 5kb মিনিফাই এবং জিজিপড।

এটা দ্রুত।
লিটের টেমপ্লেটিং সিস্টেম, lit-html, কে React এর VDOM এর সাথে তুলনা করে এমন পাবলিক বেঞ্চমার্কে , lit-html সবচেয়ে খারাপ ক্ষেত্রে React এর চেয়ে 8-10% দ্রুত এবং সাধারণ ব্যবহারের ক্ষেত্রে 50%+ দ্রুত বেরিয়ে আসে।
LitElement (Lit-এর কম্পোনেন্ট বেস ক্লাস) lit-html-এ ন্যূনতম ওভারহেড যোগ করে, কিন্তু মেমরি ব্যবহার এবং ইন্টারঅ্যাকশন এবং স্টার্টআপ সময়ের মতো কম্পোনেন্ট বৈশিষ্ট্যগুলির তুলনা করলে React-এর কর্মক্ষমতাকে 16-30% ছাড়িয়ে যায় ।

কোনও নির্মাণের প্রয়োজন নেই
ES মডিউল এবং ট্যাগযুক্ত টেমপ্লেট লিটারেলের মতো নতুন ব্রাউজার বৈশিষ্ট্য সহ, Lit চালানোর জন্য সংকলনের প্রয়োজন হয় না । এর অর্থ হল ডেভ এনভায়রনমেন্টগুলি একটি স্ক্রিপ্ট ট্যাগ + একটি ব্রাউজার + একটি সার্ভার দিয়ে সেট আপ করা যেতে পারে এবং আপনি প্রস্তুত এবং চলমান।
ES মডিউল এবং স্কাইপ্যাক বা UNPKG এর মতো আধুনিক CDN এর সাথে, শুরু করার জন্য আপনার NPM এর প্রয়োজন নাও হতে পারে!
যদিও, আপনি যদি চান, তবুও আপনি Lit কোড তৈরি এবং অপ্টিমাইজ করতে পারেন । নেটিভ ES মডিউলগুলির চারপাশে সাম্প্রতিক ডেভেলপার একত্রীকরণ Lit-এর জন্য ভালো হয়েছে - Lit হল কেবল সাধারণ জাভাস্ক্রিপ্ট এবং ফ্রেমওয়ার্ক-নির্দিষ্ট CLI বা বিল্ড হ্যান্ডলিং-এর কোনও প্রয়োজন নেই ।
ফ্রেমওয়ার্ক অজ্ঞেয়বাদী
লিটের কম্পোনেন্টগুলো ওয়েব কম্পোনেন্টস নামক ওয়েব স্ট্যান্ডার্ডের একটি সেট থেকে তৈরি। এর মানে হল লিটে একটি কম্পোনেন্ট তৈরি করা বর্তমান এবং ভবিষ্যতের ফ্রেমওয়ার্কে কাজ করবে । যদি এটি HTML উপাদান সমর্থন করে, তাহলে এটি ওয়েব কম্পোনেন্টস সমর্থন করে।
ফ্রেমওয়ার্ক ইন্টারঅপের একমাত্র সমস্যা হল যখন ফ্রেমওয়ার্কগুলিতে DOM-এর জন্য সীমাবদ্ধ সমর্থন থাকে। React এই ফ্রেমওয়ার্কগুলির মধ্যে একটি, তবে এটি Refs-এর মাধ্যমে এস্কেপ হ্যাচগুলিকে অনুমতি দেয় এবং React-এ Refs ডেভেলপারদের জন্য ভালো অভিজ্ঞতা নয়।
লিট টিম @lit-labs/react নামে একটি পরীক্ষামূলক প্রকল্পে কাজ করছে যা স্বয়ংক্রিয়ভাবে আপনার লিট উপাদানগুলিকে বিশ্লেষণ করবে এবং একটি রিঅ্যাক্ট র্যাপার তৈরি করবে যাতে আপনাকে রেফ ব্যবহার করতে না হয়।
অতিরিক্তভাবে, কাস্টম এলিমেন্টস এভরিহোয়ার আপনাকে দেখাবে কোন ফ্রেমওয়ার্ক এবং লাইব্রেরিগুলি কাস্টম এলিমেন্টগুলির সাথে সুন্দরভাবে কাজ করে!
প্রথম শ্রেণীর টাইপস্ক্রিপ্ট সাপোর্ট
যদিও আপনার সমস্ত লিট কোড জাভাস্ক্রিপ্টে লেখা সম্ভব, লিট টাইপস্ক্রিপ্টে লেখা হয় এবং লিট টিম ডেভেলপারদেরও টাইপস্ক্রিপ্ট ব্যবহার করার পরামর্শ দেয়!
lit-analyzer এবং lit-plugin সাহায্যে ডেভেলপমেন্ট এবং বিল্ড উভয় সময়েই লিট টেমপ্লেটগুলিতে টাইপস্ক্রিপ্ট টাইপ চেকিং এবং ইন্টেলিসেন্স নিয়ে আসা প্রকল্পগুলি বজায় রাখতে লিট টিম লিট সম্প্রদায়ের সাথে কাজ করছে।


ডেভ টুলগুলি ব্রাউজারেই তৈরি করা হয়
Lit কম্পোনেন্টগুলো DOM-এর HTML এলিমেন্ট মাত্র । এর মানে হল আপনার কম্পোনেন্টগুলো পরিদর্শন করার জন্য, আপনার ব্রাউজারের জন্য কোনও টুল বা এক্সেনশন ইনস্টল করার প্রয়োজন নেই ।
আপনি কেবল ডেভেলপার টুল খুলতে পারেন, একটি উপাদান নির্বাচন করতে পারেন এবং এর বৈশিষ্ট্য বা অবস্থা অন্বেষণ করতে পারেন।

এটি সার্ভার সাইড রেন্ডারিং (SSR) এর কথা মাথায় রেখে তৈরি করা হয়েছে।
Lit 2 তৈরি করা হয়েছে SSR সাপোর্টের কথা মাথায় রেখে। এই কোডল্যাব লেখার সময়, Lit টিম এখনও SSR টুলগুলিকে স্থিতিশীল আকারে প্রকাশ করেনি, তবে Lit টিম ইতিমধ্যেই Google পণ্যগুলিতে সার্ভার সাইড রেন্ডার করা উপাদানগুলি স্থাপন করছে এবং React অ্যাপ্লিকেশনগুলির মধ্যে SSR পরীক্ষা করেছে। Lit টিম শীঘ্রই GitHub-এ এই টুলগুলি বহিরাগতভাবে প্রকাশ করার আশা করছে।
ইতিমধ্যে আপনি এখানে লিট টিমের অগ্রগতি অনুসরণ করতে পারেন।
এটি কম কিনুন।
Lit ব্যবহার করার জন্য খুব বেশি প্রতিশ্রুতির প্রয়োজন হয় না! আপনি Lit-এ কম্পোনেন্ট তৈরি করতে পারেন এবং আপনার বিদ্যমান প্রোজেক্টে যোগ করতে পারেন। যদি আপনার পছন্দ না হয়, তাহলে আপনাকে একবারে পুরো অ্যাপটি রূপান্তর করতে হবে না কারণ ওয়েব কম্পোনেন্টগুলি অন্যান্য ফ্রেমওয়ার্কে কাজ করে!
আপনি কি Lit-এ একটি সম্পূর্ণ অ্যাপ তৈরি করেছেন এবং অন্য কিছুতে পরিবর্তন করতে চান? আচ্ছা, তাহলে আপনি আপনার বর্তমান Lit অ্যাপ্লিকেশনটি আপনার নতুন ফ্রেমওয়ার্কের ভিতরে রাখতে পারেন এবং নতুন ফ্রেমওয়ার্কের উপাদানগুলিতে আপনার যা ইচ্ছা স্থানান্তর করতে পারেন।
উপরন্তু, অনেক আধুনিক ফ্রেমওয়ার্ক ওয়েব উপাদানগুলিতে আউটপুট সমর্থন করে , যার অর্থ হল তারা সাধারণত একটি লিট উপাদানের ভিতরেই ফিট করতে পারে।
৩. খেলার মাঠটি সেট আপ করা এবং অন্বেষণ করা
এই কোডল্যাবটি করার দুটি উপায় আছে:
- আপনি এটি সম্পূর্ণ অনলাইনে, ব্রাউজারে করতে পারবেন।
- (উন্নত) আপনি VS কোড ব্যবহার করে আপনার স্থানীয় মেশিনে এটি করতে পারেন।
কোড অ্যাক্সেস করা হচ্ছে
কোডল্যাব জুড়ে লিট খেলার মাঠের লিঙ্কগুলি এইভাবে থাকবে:
খেলার মাঠ হল একটি কোড স্যান্ডবক্স যা সম্পূর্ণরূপে আপনার ব্রাউজারে চলে। এটি টাইপস্ক্রিপ্ট এবং জাভাস্ক্রিপ্ট ফাইলগুলি কম্পাইল এবং চালাতে পারে এবং এটি স্বয়ংক্রিয়ভাবে নোড মডিউলগুলিতে আমদানিগুলি সমাধান করতে পারে। যেমন
// before
import './my-file.js';
import 'lit';
// after
import './my-file.js';
import 'https://cdn.skypack.dev/lit';
আপনি লিট খেলার মাঠে পুরো টিউটোরিয়ালটি করতে পারেন, এই চেকপয়েন্টগুলিকে শুরুর পয়েন্ট হিসেবে ব্যবহার করে। আপনি যদি VS কোড ব্যবহার করেন, তাহলে আপনি যেকোনো ধাপের জন্য শুরুর কোড ডাউনলোড করতে এবং আপনার কাজ পরীক্ষা করতে এই চেকপয়েন্টগুলি ব্যবহার করতে পারেন।
আলোকিত খেলার মাঠের UI অন্বেষণ করা

লিট প্লেগ্রাউন্ড UI স্ক্রিনশটটি এই কোডল্যাবে আপনি যে বিভাগগুলি ব্যবহার করবেন তা হাইলাইট করে।
- ফাইল নির্বাচক। প্লাস বোতামটি লক্ষ্য করুন...
- ফাইল সম্পাদক।
- কোড প্রিভিউ।
- পুনরায় লোড বোতাম।
- ডাউনলোড বোতাম।
ভিএস কোড সেটআপ (উন্নত)
এই VS কোড সেটআপ ব্যবহারের সুবিধাগুলি এখানে দেওয়া হল:
- টেমপ্লেটের ধরণ পরীক্ষা করা হচ্ছে
- টেমপ্লেট ইন্টেলিসেন্স এবং অটোকমপ্লিশন
যদি আপনার NPM, VS কোড ( lit-plugin প্লাগইন সহ) ইতিমধ্যেই ইনস্টল করা থাকে এবং আপনি সেই পরিবেশটি কীভাবে ব্যবহার করতে হয় তা জানেন, তাহলে আপনি নিম্নলিখিতগুলি করে এই প্রকল্পগুলি ডাউনলোড করে শুরু করতে পারেন:
- ডাউনলোড বোতাম টিপুন
- টার ফাইলের বিষয়বস্তু একটি ডিরেক্টরিতে বের করুন
- (যদি TS হয়) তাহলে একটি দ্রুত tsconfig সেট আপ করুন যা es মডিউল এবং es2015+ আউটপুট করে
- এমন একটি ডেভ সার্ভার ইনস্টল করুন যা বেয়ার মডিউল স্পেসিফায়ারগুলি সমাধান করতে পারে (লিট টিম @web/dev-server সুপারিশ করে)
- এখানে
package.jsonএকটি উদাহরণ দেওয়া হল
- এখানে
- ডেভ সার্ভারটি চালান এবং আপনার ব্রাউজারটি খুলুন (যদি আপনি @web/dev-server ব্যবহার করেন তবে আপনি
npx web-dev-server --node-resolve --watch --openব্যবহার করতে পারেন)- যদি আপনি উদাহরণ
package.jsonব্যবহার করেন তাহলেnpm run devব্যবহার করুন
- যদি আপনি উদাহরণ
৪. জেএসএক্স এবং টেমপ্লেটিং
এই বিভাগে, আপনি লিট ভাষায় টেমপ্লেটিংয়ের মূল বিষয়গুলি শিখবেন।
JSX এবং লিট টেমপ্লেট
JSX হল জাভাস্ক্রিপ্টের একটি সিনট্যাক্স এক্সটেনশন যা React ব্যবহারকারীদের তাদের জাভাস্ক্রিপ্ট কোডে সহজেই টেমপ্লেট লিখতে সাহায্য করে। Lit টেমপ্লেটগুলি একই রকমের একটি উদ্দেশ্য পূরণ করে: একটি উপাদানের UI কে তার অবস্থার একটি ফাংশন হিসাবে প্রকাশ করা।
মৌলিক বাক্য গঠন
React-এ আপনি JSX hello world এভাবে রেন্ডার করবেন:
import 'react';
import ReactDOM from 'react-dom';
const name = 'Josh Perez';
const element = (
<>
<h1>Hello, {name}</h1>
<div>How are you?</div>
</>
);
ReactDOM.render(
element,
mountNode
);
উপরের উদাহরণে, দুটি উপাদান এবং একটি অন্তর্ভুক্ত "name" ভেরিয়েবল রয়েছে। Lit-এ আপনি নিম্নলিখিতগুলি করবেন:
import {html, render} from 'lit';
const name = 'Josh Perez';
const element = html`
<h1>Hello, ${name}</h1>
<div>How are you?</div>`;
render(
element,
mountNode
);
লক্ষ্য করুন যে Lit টেমপ্লেটগুলির টেমপ্লেটগুলিতে একাধিক উপাদান গোষ্ঠীভুক্ত করার জন্য React Fragment-এর প্রয়োজন হয় না।
লিট-এ, টেমপ্লেটগুলিকে একটি html ট্যাগযুক্ত টেমপ্লেট LIT eral দিয়ে মোড়ানো হয়, যা থেকে লিট তার নাম পেয়েছে!
টেমপ্লেট মান
লিট টেমপ্লেটগুলি অন্যান্য লিট টেমপ্লেট গ্রহণ করতে পারে, যা TemplateResult নামে পরিচিত। উদাহরণস্বরূপ, name ইটালিক ( <i> ) ট্যাগে মুড়ে একটি ট্যাগযুক্ত টেমপ্লেট দিয়ে মুড়ে দিন। NB একক উদ্ধৃতি অক্ষর ( ' ) ব্যবহার না করে ব্যাকটিক অক্ষর ( ` ) ব্যবহার করতে ভুলবেন না।
import {html, render} from 'lit';
const name = html`<i>Josh Perez</i>`;
const element = html`
<h1>Hello, ${name}</h1>
<div>How are you?</div>`;
render(
element,
mountNode
);
Lit TemplateResult গুলি অ্যারে, স্ট্রিং, অন্যান্য TemplateResult গুলি, সেইসাথে নির্দেশিকা গ্রহণ করতে পারে।
একটি অনুশীলনের জন্য, নিম্নলিখিত React কোডটিকে Lit-এ রূপান্তর করার চেষ্টা করুন:
const itemsToBuy = [
<li>Bananas</li>,
<li>oranges</li>,
<li>apples</li>,
<li>grapes</li>
];
const element = (
<>
<h1>Things to buy:</h1>
<ol>
{itemsToBuy}
</ol>
</>);
ReactDOM.render(
element,
mountNode
);
উত্তর:
import {html, render} from 'lit';
const itemsToBuy = [
html`<li>Bananas</li>`,
html`<li>oranges</li>`,
html`<li>apples</li>`,
html`<li>grapes</li>`
];
const element = html`
<h1>Things to buy:</h1>
<ol>
${itemsToBuy}
</ol>`;
render(
element,
mountNode
);
পাসিং এবং প্রপস সেট করা
JSX এবং Lit এর সিনট্যাক্সের মধ্যে সবচেয়ে বড় পার্থক্য হল ডেটা বাইন্ডিং সিনট্যাক্স। উদাহরণস্বরূপ, বাইন্ডিং সহ এই React ইনপুটটি নিন:
const disabled = false;
const label = 'my label';
const myClass = 'my-class';
const value = 'my value';
const element =
<input
disabled={disabled}
className={`static-class ${myClass}`}
defaultValue={value}/>;
ReactDOM.render(
element,
mountNode
);
উপরের উদাহরণে, একটি ইনপুট সংজ্ঞায়িত করা হয়েছে যা নিম্নলিখিত কাজগুলি করে:
- একটি সংজ্ঞায়িত ভেরিয়েবলে নিষ্ক্রিয় সেট (এই ক্ষেত্রে মিথ্যা)
- ক্লাসটিকে
static-classপ্লাস একটি ভেরিয়েবলে সেট করে (এই ক্ষেত্রে"static-class my-class") - একটি ডিফল্ট মান সেট করে
লিট-এ আপনি নিম্নলিখিতগুলি করবেন:
import {html, render} from 'lit';
const disabled = false;
const label = 'my label';
const myClass = 'my-class';
const value = 'my value';
const element = html`
<input
?disabled=${disabled}
class="static-class ${myClass}"
.value=${value}>`;
render(
element,
mountNode
);
Lit উদাহরণে disabled অ্যাট্রিবিউট টগল করার জন্য একটি বুলিয়ান বাইন্ডিং যোগ করা হয়েছে।
এরপর, className পরিবর্তে class অ্যাট্রিবিউটের সাথে সরাসরি একটি বাইন্ডিং আছে। class অ্যাট্রিবিউটে একাধিক বাইন্ডিং যোগ করা যেতে পারে, যদি না আপনি classMap নির্দেশিকা ব্যবহার করেন যা ক্লাস টগল করার জন্য একটি ঘোষণামূলক সহায়ক।
অবশেষে, ইনপুটে value প্রোপার্টি সেট করা হয়। React এর বিপরীতে, এটি ইনপুট এলিমেন্টকে কেবল পঠনযোগ্য হিসেবে সেট করবে না কারণ এটি ইনপুটের নেটিভ বাস্তবায়ন এবং আচরণ অনুসরণ করে।
লিট প্রপ বাইন্ডিং সিনট্যাক্স
html`<my-element ?attribute-name=${booleanVar}>`;
-
?প্রিফিক্স হলো একটি এলিমেন্টের উপর একটি অ্যাট্রিবিউট টগল করার জন্য বাইন্ডিং সিনট্যাক্স। -
inputRef.toggleAttribute('attribute-name', booleanVar)এর সমতুল্য - যেসব উপাদান
disabledকেdisabled="false"হিসেবে ব্যবহার করে, তাদের জন্য উপযোগী, DOM এখনও true হিসেবে পড়ে কারণinputElement.hasAttribute('disabled') === true
html`<my-element .property-name=${anyVar}>`;
.প্রিফিক্স হলো একটি এলিমেন্টের প্রোপার্টি সেট করার জন্য বাইন্ডিং সিনট্যাক্স।-
inputRef.propertyName = anyVarএর সমতুল্য - অবজেক্ট, অ্যারে, অথবা ক্লাসের মতো জটিল ডেটা পাস করার জন্য ভালো
html`<my-element attribute-name=${stringVar}>`;
- একটি এলিমেন্টের অ্যাট্রিবিউটের সাথে আবদ্ধ হয়
-
inputRef.setAttribute('attribute-name', stringVar)এর সমতুল্য - মৌলিক মান, স্টাইল নিয়ম নির্বাচক এবং কোয়েরি নির্বাচকদের জন্য ভালো
পাসিং হ্যান্ডলার
const disabled = false;
const label = 'my label';
const myClass = 'my-class';
const value = 'my value';
const element =
<input
onClick={() => console.log('click')}
onChange={e => console.log(e.target.value)} />;
ReactDOM.render(
element,
mountNode
);
উপরের উদাহরণে, একটি ইনপুট সংজ্ঞায়িত করা হয়েছে যা নিম্নলিখিত কাজগুলি করে:
- ইনপুট ক্লিক করার সময় "ক্লিক" শব্দটি লগ করুন
- ব্যবহারকারী যখন একটি অক্ষর টাইপ করে তখন ইনপুটের মান লগ করুন।
লিট-এ আপনি নিম্নলিখিতগুলি করবেন:
import {html, render} from 'lit';
const disabled = false;
const label = 'my label';
const myClass = 'my-class';
const value = 'my value';
const element = html`
<input
@click=${() => console.log('click')}
@input=${e => console.log(e.target.value)}>`;
render(
element,
mountNode
);
লিট উদাহরণে, @click সহ click ইভেন্টে একজন শ্রোতা যোগ করা হয়েছে।
এরপর, onChange ব্যবহার করার পরিবর্তে, <input> এর নেটিভ input ইভেন্টের সাথে একটি বাইন্ডিং রয়েছে কারণ নেটিভ change ইভেন্টটি কেবল blur উপর কার্যকর হয় (এই ইভেন্টগুলির উপর প্রতিক্রিয়া সারাংশ)।
লিট ইভেন্ট হ্যান্ডলার সিনট্যাক্স
html`<my-element @event-name=${() => {...}}></my-element>`;
@প্রিফিক্স হল একটি ইভেন্ট লিসেনারের জন্য বাইন্ডিং সিনট্যাক্স।-
inputRef.addEventListener('event-name', ...)এর সমতুল্য - নেটিভ DOM ইভেন্টের নাম ব্যবহার করে
৫. উপাদান এবং প্রপস
এই বিভাগে আপনি Lit ক্লাসের উপাদান এবং ফাংশন সম্পর্কে শিখবেন। পরবর্তী বিভাগে State এবং Hooks সম্পর্কে আরও বিস্তারিত আলোচনা করা হয়েছে।
ক্লাস কম্পোনেন্টস এবং লিটএলিমেন্ট
একটি React ক্লাস কম্পোনেন্টের Lit সমতুল্য হল LitElement, এবং Lit-এর "প্রতিক্রিয়াশীল বৈশিষ্ট্য" ধারণাটি হল React-এর প্রপস এবং অবস্থার সংমিশ্রণ। উদাহরণস্বরূপ:
import React from 'react';
import ReactDOM from 'react-dom';
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = {name: ''};
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
const element = <Welcome name="Elliott"/>
ReactDOM.render(
element,
mountNode
);
উপরের উদাহরণে একটি React উপাদান রয়েছে যা:
- একটি
nameতৈরি করে -
nameএর ডিফল্ট মান empty string ("") এ সেট করে। -
"Elliott"nameপুনরায় বরাদ্দ করে
LitElement-এ আপনি এইভাবে এটি করবেন
টাইপস্ক্রিপ্টে:
import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';
@customElement('welcome-banner')
class WelcomeBanner extends LitElement {
@property({type: String})
name = '';
render() {
return html`<h1>Hello, ${this.name}</h1>`
}
}
জাভাস্ক্রিপ্টে:
import {LitElement, html} from 'lit';
class WelcomeBanner extends LitElement {
static get properties() {
return {
name: {type: String}
}
}
constructor() {
super();
this.name = '';
}
render() {
return html`<h1>Hello, ${this.name}</h1>`
}
}
customElements.define('welcome-banner', WelcomeBanner);
এবং HTML ফাইলে:
<!-- index.html -->
<head>
<script type="module" src="./index.js"></script>
</head>
<body>
<welcome-banner name="Elliott"></welcome-banner>
</body>
উপরের উদাহরণে কী ঘটছে তার একটি পর্যালোচনা:
@property({type: String})
name = '';
- একটি পাবলিক রিঅ্যাকটিভ প্রোপার্টি সংজ্ঞায়িত করে - যা আপনার কম্পোনেন্টের পাবলিক API-এর একটি অংশ।
- আপনার কম্পোনেন্টের একটি বৈশিষ্ট্য (ডিফল্টরূপে) এবং একটি বৈশিষ্ট্য প্রকাশ করে।
- কম্পোনেন্টের অ্যাট্রিবিউট (যা স্ট্রিং) কে একটি মানে রূপান্তর করার পদ্ধতি নির্ধারণ করে।
static get properties() {
return {
name: {type: String}
}
}
- এটি
@propertyTS ডেকোরেটরের মতো একই কাজ করে কিন্তু জাভাস্ক্রিপ্টে নেটিভভাবে চলে।
render() {
return html`<h1>Hello, ${this.name}</h1>`
}
- যখনই কোনও প্রতিক্রিয়াশীল সম্পত্তি পরিবর্তন করা হয় তখন এটি বলা হয়
@customElement('welcome-banner')
class WelcomeBanner extends LitElement {
...
}
- এটি একটি HTML Element ট্যাগের নামকে একটি ক্লাস সংজ্ঞার সাথে সংযুক্ত করে
- কাস্টম এলিমেন্টস স্ট্যান্ডার্ডের কারণে, ট্যাগের নামে অবশ্যই একটি হাইফেন (-) থাকতে হবে।
- LitElement-এ
thisকাস্টম এলিমেন্টের উদাহরণকে বোঝায় (এই ক্ষেত্রে<welcome-banner>)
customElements.define('welcome-banner', WelcomeBanner);
- এটি
@customElementTS ডেকোরেটরের জাভাস্ক্রিপ্ট সমতুল্য।
<head>
<script type="module" src="./index.js"></script>
</head>
- কাস্টম এলিমেন্টের সংজ্ঞা আমদানি করে।
<body>
<welcome-banner name="Elliott"></welcome-banner>
</body>
- পৃষ্ঠায় কাস্টম উপাদান যোগ করে।
-
nameবৈশিষ্ট্যটি'Elliott'তে সেট করে।
ফাংশন উপাদান
Lit-এ কোনও ফাংশন কম্পোনেন্টের ১:১ ব্যাখ্যা নেই কারণ এটি JSX বা প্রিপ্রসেসর ব্যবহার করে না। যদিও, এমন একটি ফাংশন রচনা করা বেশ সহজ যা বৈশিষ্ট্য গ্রহণ করে এবং সেই বৈশিষ্ট্যগুলির উপর ভিত্তি করে DOM রেন্ডার করে। উদাহরণস্বরূপ:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Elliott"/>
ReactDOM.render(
element,
mountNode
);
লিট-এ এটি হবে:
import {html, render} from 'lit';
function Welcome(props) {
return html`<h1>Hello, ${props.name}</h1>`;
}
render(
Welcome({name: 'Elliott'}),
document.body.querySelector('#root')
);
৬. অবস্থা ও জীবনচক্র
এই বিভাগে আপনি লিটের অবস্থা এবং জীবনচক্র সম্পর্কে শিখবেন।
রাজ্য
লিটের "রিঅ্যাক্টিভ প্রোপার্টিজ" ধারণাটি রিঅ্যাক্টের অবস্থা এবং প্রপসের মিশ্রণ। রিঅ্যাক্টিভ প্রোপার্টিজ, যখন পরিবর্তিত হয়, তখন কম্পোনেন্টের জীবনচক্রকে ট্রিগার করতে পারে। রিঅ্যাক্টিভ প্রোপার্টিজ দুটি রূপে আসে:
পাবলিক রিঅ্যাকটিভ বৈশিষ্ট্য
// React
import React from 'react';
class MyEl extends React.Component {
constructor(props) {
super(props)
this.state = {name: 'there'}
}
componentWillReceiveProps(nextProps) {
if (this.props.name !== nextProps.name) {
this.setState({name: nextProps.name})
}
}
}
// Lit (TS)
import {LitElement} from 'lit';
import {property} from 'lit/decorators.js';
class MyEl extends LitElement {
@property() name = 'there';
}
@propertyদ্বারা সংজ্ঞায়িত- React এর প্রপস এবং স্টেটের মতো কিন্তু পরিবর্তনযোগ্য
- পাবলিক এপিআই যা কম্পোনেন্টের গ্রাহকরা অ্যাক্সেস এবং সেট করেন
অভ্যন্তরীণ প্রতিক্রিয়াশীল অবস্থা
// React
import React from 'react';
class MyEl extends React.Component {
constructor(props) {
super(props)
this.state = {name: 'there'}
}
}
// Lit (TS)
import {LitElement} from 'lit';
import {state} from 'lit/decorators.js';
class MyEl extends LitElement {
@state() name = 'there';
}
@stateদ্বারা সংজ্ঞায়িত- React এর অবস্থা অনুরূপ কিন্তু পরিবর্তনযোগ্য
- ব্যক্তিগত অভ্যন্তরীণ অবস্থা যা সাধারণত উপাদান বা উপশ্রেণীর মধ্যে থেকে অ্যাক্সেস করা হয়
জীবনচক্র
লিট লাইফসাইকেলটি রিঅ্যাক্টের মতোই, তবে কিছু উল্লেখযোগ্য পার্থক্য রয়েছে।
constructor
// React (js)
import React from 'react';
class MyEl extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this._privateProp = 'private';
}
}
// Lit (ts)
class MyEl extends LitElement {
@property({type: Number}) counter = 0;
private _privateProp = 'private';
}
// Lit (js)
class MyEl extends LitElement {
static get properties() {
return { counter: {type: Number} }
}
constructor() {
this.counter = 0;
this._privateProp = 'private';
}
}
- লিট ইকুয়ালিউয়াল হল
constructor - সুপার কলে কিছু পাস করার দরকার নেই।
- (সম্পূর্ণ অন্তর্ভুক্ত নয়) দ্বারা আহ্বান করা হয়েছে:
-
document.createElement -
document.innerHTML -
new ComponentClass() - যদি পৃষ্ঠায় একটি অ-আপগ্রেড করা ট্যাগের নাম থাকে এবং সংজ্ঞাটি
@customElementঅথবাcustomElements.defineএ লোড এবং নিবন্ধিত থাকে
-
- ফাংশনে React এর
constructorঅনুরূপ
render
// React
render() {
return <div>Hello World</div>
}
// Lit
render() {
return html`<div>Hello World</div>`;
}
- লিট ইকুয়ালিউশনও
render - যেকোনো রেন্ডারেবল ফলাফল যেমন
TemplateResultবাstringইত্যাদি ফেরত দিতে পারে। - React এর মতোই,
render()একটি বিশুদ্ধ ফাংশন হওয়া উচিত - যে নোড
createRenderRoot()রিটার্ন করে সেখানে রেন্ডার করবে (ডিফল্টরূপেShadowRoot)
componentDidMount
componentDidMount হল Lit-এর firstUpdated এবং connectedCallback লাইফসাইকেল কলব্যাকের সংমিশ্রণের অনুরূপ।
firstUpdated
import Chart from 'chart.js';
// React
componentDidMount() {
this._chart = new Chart(this.chartElRef.current, {...});
}
// Lit
firstUpdated() {
this._chart = new Chart(this.chartEl, {...});
}
- কম্পোনেন্টের টেমপ্লেটটি কম্পোনেন্টের রুটে প্রথমবার রেন্ডার করার সময় কল করা হয়
- শুধুমাত্র তখনই কল করা হবে যখন উপাদানটি সংযুক্ত থাকে, যেমন
document.createElement('my-component')এর মাধ্যমে কল করা হবে না যতক্ষণ না সেই নোডটি DOM ট্রিতে যুক্ত করা হয়। - এটি কম্পোনেন্ট সেটআপ করার জন্য একটি ভালো জায়গা যেখানে কম্পোনেন্ট দ্বারা রেন্ডার করা DOM প্রয়োজন হয়।
- React এর
componentDidMountবিপরীতেfirstUpdatedএ reactive properties এ পরিবর্তন করলে re-render হবে, যদিও ব্রাউজার সাধারণত একই ফ্রেমে পরিবর্তনগুলিকে ব্যাচ করবে। যদি এই পরিবর্তনগুলির জন্য root এর DOM অ্যাক্সেসের প্রয়োজন না হয়, তাহলে সাধারণতwillUpdateএ যাওয়া উচিত।
connectedCallback
// React
componentDidMount() {
this.window.addEventListener('resize', this.boundOnResize);
}
// Lit
connectedCallback() {
super.connectedCallback();
this.window.addEventListener('resize', this.boundOnResize);
}
- DOM ট্রিতে কাস্টম এলিমেন্ট ঢোকানো হলে কল করা হয়
- React উপাদানগুলির বিপরীতে, যখন কাস্টম উপাদানগুলি DOM থেকে বিচ্ছিন্ন করা হয়, তখন সেগুলি ধ্বংস হয় না এবং এইভাবে একাধিকবার "সংযুক্ত" করা যেতে পারে।
-
firstUpdatedআর কল করা হবে না
-
- DOM পুনরায় আরম্ভ করার জন্য অথবা সংযোগ বিচ্ছিন্ন করার সময় পরিষ্কার করা ইভেন্ট লিসেনারের পুনরায় সংযুক্ত করার জন্য কার্যকর।
- দ্রষ্টব্য:
firstUpdatedআগেconnectedCallbackকল করা যেতে পারে তাই প্রথম কলে, DOM উপলব্ধ নাও হতে পারে।
componentDidUpdate
// React
componentDidUpdate(prevProps) {
if (this.props.title !== prevProps.title) {
this._chart.setTitle(this.props.title);
}
}
// Lit (ts)
updated(prevProps: PropertyValues<this>) {
if (prevProps.has('title')) {
this._chart.setTitle(this.title);
}
}
- লিট ইকুইলুয়েভেল
updatedহয়েছে ("আপডেট" এর ইংরেজি অতীত কাল ব্যবহার করে) - React এর বিপরীতে, প্রাথমিক রেন্ডারেও
updatedবলা হয়। - ফাংশনটি React এর
componentDidUpdateঅনুরূপ।
componentWillUnmount
// React
componentWillUnmount() {
this.window.removeEventListener('resize', this.boundOnResize);
}
// Lit
disconnectedCallback() {
super.disconnectedCallback();
this.window.removeEventListener('resize', this.boundOnResize);
}
- লিট ইকুইলুয়েলেবল
disconnectedCallbackমতো। - React উপাদানগুলির বিপরীতে, যখন কাস্টম উপাদানগুলি DOM থেকে বিচ্ছিন্ন করা হয় তখন উপাদানটি ধ্বংস হয় না।
-
componentWillUnmountবিপরীতে,disconnectedCallbackট্রি থেকে উপাদানটি সরানোর পরে কল করা হয়। - রুটের ভেতরে থাকা DOM এখনও রুটের সাবট্রির সাথে সংযুক্ত থাকে।
- ইভেন্ট লিসেনার্স এবং লিকি রেফারেন্স পরিষ্কার করার জন্য কার্যকর যাতে ব্রাউজারটি কম্পোনেন্টটি আবর্জনা সংগ্রহ করতে পারে।
ব্যায়াম
import React from 'react';
import ReactDOM from 'react-dom';
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 (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
উপরের উদাহরণে, একটি সাধারণ ঘড়ি আছে যা নিম্নলিখিত কাজগুলি করে:
- এটি "হ্যালো ওয়ার্ল্ড! এটা" রেন্ডার করে এবং তারপর সময় প্রদর্শন করে
- প্রতি সেকেন্ডে এটি ঘড়ি আপডেট করবে
- নামিয়ে দিলে, এটি টিক কল করার ব্যবধানটি পরিষ্কার করে
প্রথমে কম্পোনেন্ট ক্লাস ঘোষণা দিয়ে শুরু করুন:
// Lit (TS)
// some imports here are imported in advance
import {LitElement, html} from 'lit';
import {customElement, state} from 'lit/decorators.js';
@customElement('lit-clock')
class LitClock extends LitElement {
}
// Lit (JS)
// `html` is imported in advance
import {LitElement, html} from 'lit';
class LitClock extends LitElement {
}
customElements.define('lit-clock', LitClock);
এরপর, date ইনিশিয়ালাইজ করুন এবং @state দিয়ে এটিকে একটি অভ্যন্তরীণ প্রতিক্রিয়াশীল সম্পত্তি ঘোষণা করুন কারণ কম্পোনেন্টের ব্যবহারকারীরা সরাসরি date সেট করবেন না।
// Lit (TS)
import {LitElement, html} from 'lit';
import {customElement, state} from 'lit/decorators.js';
@customElement('lit-clock')
class LitClock extends LitElement {
@state() // declares internal reactive prop
private date = new Date(); // initialization
}
// Lit (JS)
import {LitElement, html} from 'lit';
class LitClock extends LitElement {
static get properties() {
return {
// declares internal reactive prop
date: {state: true}
}
}
constructor() {
super();
// initialization
this.date = new Date();
}
}
customElements.define('lit-clock', LitClock);
এরপর, টেমপ্লেটটি রেন্ডার করুন।
// Lit (JS & TS)
render() {
return html`
<div>
<h1>Hello, World!</h1>
<h2>It is ${this.date.toLocaleTimeString()}.</h2>
</div>
`;
}
এখন, টিক পদ্ধতিটি বাস্তবায়ন করুন।
tick() {
this.date = new Date();
}
এরপর আসে componentDidMount বাস্তবায়নের প্রক্রিয়া। আবার, Lit অ্যানালগটি firstUpdated এবং connectedCallback এর মিশ্রণ। এই কম্পোনেন্টের ক্ষেত্রে, setInterval দিয়ে কল করার জন্য tick root এর ভিতরে DOM অ্যাক্সেসের প্রয়োজন হয় না। অতিরিক্তভাবে, ডকুমেন্ট ট্রি থেকে উপাদানটি সরানো হলে ব্যবধানটি পরিষ্কার হয়ে যাবে, তাই যদি এটি পুনরায় সংযুক্ত করা হয়, তাহলে ব্যবধানটি আবার শুরু করতে হবে। সুতরাং, connectedCallback এখানে একটি ভাল পছন্দ।
// Lit (TS)
@customElement('lit-clock')
class LitClock extends LitElement {
@state()
private date = new Date();
// initialize timerId for TS
private timerId = -1 as unknown as ReturnType<typeof setTimeout>;
connectedCallback() {
super.connectedCallback();
this.timerId = setInterval(
() => this.tick(),
1000
);
}
...
}
// Lit (JS)
constructor() {
super();
// initialization
this.date = new Date();
this.timerId = -1; // initialize timerId for JS
}
connectedCallback() {
super.connectedCallback();
this.timerId = setInterval(
() => this.tick(),
1000
);
}
অবশেষে, ইন্টারভালটি পরিষ্কার করুন যাতে ডকুমেন্ট ট্রি থেকে উপাদানটি সংযোগ বিচ্ছিন্ন হওয়ার পরে এটি টিকটি কার্যকর না করে।
// Lit (TS & JS)
disconnectedCallback() {
super.disconnectedCallback();
clearInterval(this.timerId);
}
সবকিছু একসাথে করলে, এটি দেখতে এরকম হওয়া উচিত:
// Lit (TS)
import {LitElement, html} from 'lit';
import {customElement, state} from 'lit/decorators.js';
@customElement('lit-clock')
class LitClock extends LitElement {
@state()
private date = new Date();
private timerId = -1 as unknown as ReturnType<typeof setTimeout>;
connectedCallback() {
super.connectedCallback();
this.timerId = setInterval(
() => this.tick(),
1000
);
}
tick() {
this.date = new Date();
}
render() {
return html`
<div>
<h1>Hello, World!</h1>
<h2>It is ${this.date.toLocaleTimeString()}.</h2>
</div>
`;
}
disconnectedCallback() {
super.disconnectedCallback();
clearInterval(this.timerId);
}
}
// Lit (JS)
import {LitElement, html} from 'lit';
class LitClock extends LitElement {
static get properties() {
return {
date: {state: true}
}
}
constructor() {
super();
this.date = new Date();
}
connectedCallback() {
super.connectedCallback();
this.timerId = setInterval(
() => this.tick(),
1000
);
}
tick() {
this.date = new Date();
}
render() {
return html`
<div>
<h1>Hello, World!</h1>
<h2>It is ${this.date.toLocaleTimeString()}.</h2>
</div>
`;
}
disconnectedCallback() {
super.disconnectedCallback();
clearInterval(this.timerId);
}
}
customElements.define('lit-clock', LitClock);
৭. হুক
এই বিভাগে, আপনি শিখবেন কিভাবে React Hook ধারণাগুলিকে Lit তে অনুবাদ করতে হয়।
রিঅ্যাক্ট হুকের ধারণাগুলি
রিঅ্যাক্ট হুক ফাংশন কম্পোনেন্টগুলিকে "হুক" অবস্থায় আনার একটি উপায় প্রদান করে। এর বেশ কিছু সুবিধা রয়েছে।
- তারা স্টেটফুল লজিকের পুনঃব্যবহারকে সহজ করে তোলে
- একটি কম্পোনেন্টকে ছোট ছোট ফাংশনে ভাগ করতে সাহায্য করুন
অতিরিক্তভাবে, ফাংশন-ভিত্তিক উপাদানগুলির উপর ফোকাস রিঅ্যাক্টের ক্লাস-ভিত্তিক সিনট্যাক্সের কিছু সমস্যা সমাধান করেছে যেমন:
-
constructorথেকেsuperpropsপাস করতে হচ্ছে -
constructorপ্রোপার্টিগুলির অগোছালো আরম্ভকরণ- এই কারণটি তখন রিঅ্যাক্ট টিম দ্বারা উল্লেখ করা হয়েছিল কিন্তু ES2019 দ্বারা সমাধান করা হয়েছিল।
-
thisফলে সৃষ্ট সমস্যাগুলি আর উপাদানটির সাথে সম্পর্কিত নয়
লিট ভাষায় রিঅ্যাক্ট হুক ধারণা
কম্পোনেন্টস এবং প্রপস বিভাগে যেমন উল্লেখ করা হয়েছে, Lit কোনও ফাংশন থেকে কাস্টম উপাদান তৈরি করার কোনও উপায় অফার করে না, তবে LitElement React ক্লাস কম্পোনেন্টগুলির বেশিরভাগ প্রধান সমস্যা সমাধান করে। উদাহরণস্বরূপ:
// React (at the time of making hooks)
import React from 'react';
import ReactDOM from 'react-dom';
class MyEl extends React.Component {
constructor(props) {
super(props); // Leaky implementation
this.state = {count: 0};
this._chart = null; // Deemed messy
}
render() {
return (
<>
<div>Num times clicked {count}</div>
<button onClick={this.clickCallback}>click me</button>
</>
);
}
clickCallback() {
// Errors because `this` no longer refers to the component
this.setState({count: this.count + 1});
}
}
// Lit (ts)
class MyEl extends LitElement {
@property({type: Number}) count = 0; // No need for constructor to set state
private _chart = null; // Public class fields introduced to JS in 2019
render() {
return html`
<div>Num times clicked ${count}</div>
<button @click=${this.clickCallback}>click me</button>`;
}
private clickCallback() {
// No error because `this` refers to component
this.count++;
}
}
লিট কীভাবে এই সমস্যাগুলি সমাধান করে?
-
constructorকোনও আর্গুমেন্ট গ্রহণ করে না - সমস্ত
@eventবাইন্ডিংthisস্বয়ংক্রিয়ভাবে বাঁধা হবে -
thisবেশিরভাগ ক্ষেত্রেই কাস্টম উপাদানের রেফারেন্সকে বোঝায় - ক্লাস প্রোপার্টি এখন ক্লাস মেম্বার হিসেবে ইনস্ট্যান্টিয়েট করা যেতে পারে। এটি কনস্ট্রাক্টর-ভিত্তিক বাস্তবায়ন পরিষ্কার করে।
প্রতিক্রিয়াশীল নিয়ন্ত্রক
হুকসের পিছনে প্রাথমিক ধারণাগুলি লিট-এ প্রতিক্রিয়াশীল নিয়ন্ত্রক হিসাবে বিদ্যমান। প্রতিক্রিয়াশীল নিয়ন্ত্রক প্যাটার্নগুলি স্টেটফুল লজিক ভাগ করে নেওয়ার, উপাদানগুলিকে ছোট, আরও মডুলার বিটে বিভক্ত করার, পাশাপাশি একটি উপাদানের আপডেট জীবনচক্রের সাথে সংযুক্ত করার অনুমতি দেয়।
একটি প্রতিক্রিয়াশীল নিয়ামক হল একটি অবজেক্ট ইন্টারফেস যা LitElement এর মতো একটি নিয়ামক হোস্টের আপডেট জীবনচক্রের সাথে সংযুক্ত হতে পারে।
একটি ReactiveController এবং একটি reactiveControllerHost এর জীবনচক্র হল:
interface ReactiveController {
hostConnected(): void;
hostUpdate(): void;
hostUpdated(): void;
hostDisconnected(): void;
}
interface ReactiveControllerHost {
addController(controller: ReactiveController): void;
removeController(controller: ReactiveController): void;
requestUpdate(): void;
readonly updateComplete: Promise<boolean>;
}
addController ব্যবহার করে একটি রিঅ্যাকটিভ কন্ট্রোলার তৈরি করে এবং হোস্টের সাথে সংযুক্ত করে, কন্ট্রোলারের জীবনচক্র হোস্টের জীবনচক্রের সাথে মিলিত হবে। উদাহরণস্বরূপ, State & Lifecycle বিভাগের ঘড়ির উদাহরণটি মনে রাখবেন:
import React from 'react';
import ReactDOM from 'react-dom';
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 (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
উপরের উদাহরণে, একটি সাধারণ ঘড়ি রয়েছে যা নিম্নলিখিত কাজগুলি করে:
- এটি "হ্যালো ওয়ার্ল্ড! এটা" রেন্ডার করে এবং তারপর সময় প্রদর্শন করে
- প্রতি সেকেন্ডে এটি ঘড়ি আপডেট করবে
- নামিয়ে দিলে, এটি টিক কল করার ব্যবধানটি পরিষ্কার করে
কম্পোনেন্ট স্ক্যাফোল্ডিং তৈরি করা
প্রথমে কম্পোনেন্ট ক্লাস ঘোষণা দিয়ে শুরু করুন এবং render ফাংশন যোগ করুন।
// Lit (TS) - index.ts
import {LitElement, html} from 'lit';
import {customElement} from 'lit/decorators.js';
@customElement('my-element')
class MyElement extends LitElement {
render() {
return html`
<div>
<h1>Hello, world!</h1>
<h2>It is ${'time to get Lit'}.</h2>
</div>
`;
}
}
// Lit (JS) - index.js
import {LitElement, html} from 'lit';
class MyElement extends LitElement {
render() {
return html`
<div>
<h1>Hello, world!</h1>
<h2>It is ${'time to get Lit'}.</h2>
</div>
`;
}
}
customElements.define('my-element', MyElement);
কন্ট্রোলার তৈরি করা হচ্ছে
এখন clock.ts এ যান এবং ClockController এর জন্য একটি ক্লাস তৈরি করুন এবং constructor সেট আপ করুন:
// Lit (TS) - clock.ts
import {ReactiveController, ReactiveControllerHost} from 'lit';
export class ClockController implements ReactiveController {
private readonly host: ReactiveControllerHost;
constructor(host: ReactiveControllerHost) {
this.host = host;
host.addController(this);
}
hostConnected() {
}
private tick() {
}
hostDisconnected() {
}
}
// Lit (JS) - clock.js
export class ClockController {
constructor(host) {
this.host = host;
host.addController(this);
}
hostConnected() {
}
tick() {
}
hostDisconnected() {
}
}
একটি রিঅ্যাকটিভ কন্ট্রোলার যেকোনোভাবে তৈরি করা যেতে পারে যতক্ষণ না এটি ReactiveController ইন্টারফেস শেয়ার করে, কিন্তু এমন একটি ক্লাস ব্যবহার করা হয় যার সাথে একটি constructor থাকে যা ReactiveControllerHost ইন্টারফেস এবং কন্ট্রোলারটি ইনিশিয়ালাইজ করার জন্য প্রয়োজনীয় অন্যান্য বৈশিষ্ট্য গ্রহণ করতে পারে, যা Lit টিম বেশিরভাগ মৌলিক ক্ষেত্রে ব্যবহার করতে পছন্দ করে।
এখন আপনাকে React লাইফসাইকেল কলব্যাকগুলিকে কন্ট্রোলার কলব্যাকে অনুবাদ করতে হবে। সংক্ষেপে:
-
componentDidMount- LitElement এর
connectedCallbackএ - কন্ট্রোলারের
hostConnected
- LitElement এর
-
ComponentWillUnmount- LitElement এর
disconnectedCallbackএ - কন্ট্রোলারের হোস্টে
hostDisconnected
- LitElement এর
React জীবনচক্রকে Lit জীবনচক্রের সাথে রূপান্তর করার বিষয়ে আরও তথ্যের জন্য, State & Lifecycle বিভাগটি দেখুন।
এরপর, hostConnected কলব্যাক এবং tick পদ্ধতিগুলি প্রয়োগ করুন, এবং State & Lifecycle বিভাগের উদাহরণে যেমন করা হয়েছে তেমন hostDisconnected এ ব্যবধান পরিষ্কার করুন।
// Lit (TS) - clock.ts
export class ClockController implements ReactiveController {
private readonly host: ReactiveControllerHost;
private interval = 0 as unknown as ReturnType<typeof setTimeout>;
date = new Date();
constructor(host: ReactiveControllerHost) {
this.host = host;
host.addController(this);
}
hostConnected() {
this.interval = setInterval(() => this.tick(), 1000);
}
private tick() {
this.date = new Date();
}
hostDisconnected() {
clearInterval(this.interval);
}
}
// Lit (JS) - clock.js
export class ClockController {
interval = 0;
host;
date = new Date();
constructor(host) {
this.host = host;
host.addController(this);
}
hostConnected() {
this.interval = setInterval(() => this.tick(), 1000);
}
tick() {
this.date = new Date();
}
hostDisconnected() {
clearInterval(this.interval);
}
}
কন্ট্রোলার ব্যবহার করে
ঘড়ি নিয়ন্ত্রক ব্যবহার করতে, নিয়ন্ত্রকটি আমদানি করুন এবং index.ts অথবা index.js এ কম্পোনেন্টটি আপডেট করুন।
// Lit (TS) - index.ts
import {LitElement, html, ReactiveController, ReactiveControllerHost} from 'lit';
import {customElement} from 'lit/decorators.js';
import {ClockController} from './clock.js';
@customElement('my-element')
class MyElement extends LitElement {
private readonly clock = new ClockController(this); // Instantiate
render() {
// Use controller
return html`
<div>
<h1>Hello, world!</h1>
<h2>It is ${this.clock.date.toLocaleTimeString()}.</h2>
</div>
`;
}
}
// Lit (JS) - index.js
import {LitElement, html} from 'lit';
import {ClockController} from './clock.js';
class MyElement extends LitElement {
clock = new ClockController(this); // Instantiate
render() {
// Use controller
return html`
<div>
<h1>Hello, world!</h1>
<h2>It is ${this.clock.date.toLocaleTimeString()}.</h2>
</div>
`;
}
}
customElements.define('my-element', MyElement);
কন্ট্রোলারটি ব্যবহার করার জন্য, আপনাকে কন্ট্রোলার হোস্ট (যা <my-element> কম্পোনেন্ট) এর একটি রেফারেন্স পাস করে কন্ট্রোলারটি ইনস্ট্যান্টিয়েট করতে হবে, এবং তারপর render পদ্ধতিতে কন্ট্রোলারটি ব্যবহার করতে হবে।
কন্ট্রোলারে রি-রেন্ডার ট্রিগার করা হচ্ছে
লক্ষ্য করুন যে এটি সময় দেখাবে, কিন্তু সময় আপডেট হচ্ছে না। এর কারণ হল কন্ট্রোলার প্রতি সেকেন্ডে তারিখ সেট করছে, কিন্তু হোস্ট আপডেট হচ্ছে না। এর কারণ হল ClockController ক্লাসে date পরিবর্তন হচ্ছে এবং কম্পোনেন্টটি আর পরিবর্তন হচ্ছে না। এর অর্থ হল কন্ট্রোলারে date সেট করার পরে, হোস্টকে host.requestUpdate() দিয়ে তার আপডেট লাইফসাইকেল চালানোর জন্য বলা প্রয়োজন।
// Lit (TS & JS) - clock.ts / clock.js
private tick() {
this.date = new Date();
this.host.requestUpdate();
}
এখন ঘড়ির কাঁটা টিক টিক করে বেজে উঠবে!
হুকের সাথে সাধারণ ব্যবহারের ক্ষেত্রে আরও গভীর তুলনার জন্য, অনুগ্রহ করে উন্নত বিষয় - হুক বিভাগটি দেখুন।
৮. শিশুরা
এই বিভাগে, আপনি শিখবেন কিভাবে লিট-এ শিশুদের পরিচালনা করার জন্য স্লট ব্যবহার করতে হয়।
স্লট এবং শিশুরা
স্লটগুলি আপনাকে উপাদানগুলিকে নেস্ট করার অনুমতি দিয়ে রচনা সক্ষম করে।
React-এ, শিশুরা প্রপসের মাধ্যমে উত্তরাধিকারসূত্রে পায়। ডিফল্ট স্লট হল props.children এবং render ফাংশন ডিফল্ট স্লটটি কোথায় স্থাপন করা হবে তা নির্ধারণ করে। উদাহরণস্বরূপ:
const MyArticle = (props) => {
return <article>{props.children}</article>;
};
মনে রাখবেন যে props.children হল React Components, HTML উপাদান নয়।
লিট ভাষায়, রেন্ডার ফাংশনে শিশুদের স্লট উপাদান ব্যবহার করে তৈরি করা হয়। লক্ষ্য করুন, শিশুদের React এর মতো একইভাবে উত্তরাধিকারসূত্রে পাওয়া যায় না। লিট ভাষায়, শিশুদের হল স্লটের সাথে সংযুক্ত HTML উপাদান। এই সংযুক্তিকে Projection বলা হয়।
@customElement("my-article")
export class MyArticle extends LitElement {
render() {
return html`
<article>
<slot></slot>
</article>
`;
}
}
একাধিক স্লট
React-এ, একাধিক স্লট যোগ করা মূলত আরও প্রপস উত্তরাধিকারসূত্রে পাওয়ার সমান।
const MyArticle = (props) => {
return (
<article>
<header>
{props.headerChildren}
</header>
<section>
{props.sectionChildren}
</section>
</article>
);
};
একইভাবে, আরও <slot> উপাদান যোগ করলে Lit-এ আরও স্লট তৈরি হয়। একাধিক স্লট name অ্যাট্রিবিউট দিয়ে সংজ্ঞায়িত করা হয়: <slot name="slot-name"> । এটি শিশুদের কোন স্লট বরাদ্দ করা হবে তা ঘোষণা করতে দেয়।
@customElement("my-article")
export class MyArticle extends LitElement {
render() {
return html`
<article>
<header>
<slot name="headerChildren"></slot>
</header>
<section>
<slot name="sectionChildren"></slot>
</section>
</article>
`;
}
}
ডিফল্ট স্লট কন্টেন্ট
যখন স্লটে কোন নোড প্রজেক্ট করা থাকে না, তখন স্লটগুলি তাদের সাবট্রি প্রদর্শন করবে। যখন নোডগুলি একটি স্লটে প্রজেক্ট করা হয়, তখন সেই স্লটটি তার সাবট্রি প্রদর্শন করবে না এবং পরিবর্তে প্রজেক্ট করা নোডগুলি প্রদর্শন করবে।
@customElement("my-element")
export class MyElement extends LitElement {
render() {
return html`
<section>
<div>
<slot name="slotWithDefault">
<p>
This message will not be rendered when children are attached to this slot!
<p>
</slot>
</div>
</section>
`;
}
}
বাচ্চাদের স্লটে বরাদ্দ করুন
React-এ, শিশুদের একটি Component-এর বৈশিষ্ট্যের মাধ্যমে স্লটে বরাদ্দ করা হয়। নীচের উদাহরণে, React উপাদানগুলি headerChildren এবং sectionChildren props-এ পাস করা হয়।
const MyNewsArticle = () => {
return (
<MyArticle
headerChildren={<h3>Extry, Extry! Read all about it!</h3>}
sectionChildren={<p>Children are props in React!</p>}
/>
);
};
লিট ভাষায়, শিশুদের slot বৈশিষ্ট্য ব্যবহার করে স্লটে বরাদ্দ করা হয়।
@customElement("my-news-article")
export class MyNewsArticle extends LitElement {
render() {
return html`
<my-article>
<h3 slot="headerChildren">
Extry, Extry! Read all about it!
</h3>
<p slot="sectionChildren">
Children are composed with slots in Lit!
</p>
</my-article>
`;
}
}
যদি কোনও ডিফল্ট স্লট না থাকে (যেমন <slot> ) এবং এমন কোনও স্লট না থাকে যার একটি name অ্যাট্রিবিউট (যেমন <slot name="foo"> ) থাকে যা কাস্টম এলিমেন্টের শিশুদের (যেমন <div slot="foo"> ) slot অ্যাট্রিবিউটের সাথে মেলে, তাহলে সেই নোডটি প্রজেক্ট করা হবে না এবং প্রদর্শিত হবে না।
৯. রেফারেন্স
মাঝে মাঝে, একজন ডেভেলপারকে HTMLElement এর API অ্যাক্সেস করার প্রয়োজন হতে পারে।
এই বিভাগে, আপনি শিখবেন কিভাবে লিট ভাষায় উপাদানের রেফারেন্স অর্জন করতে হয়।
প্রতিক্রিয়া রেফারেন্স
একটি React কম্পোনেন্টকে ফাংশন কলের একটি সিরিজে স্থানান্তরিত করা হয় যা ইনভোক করলে একটি ভার্চুয়াল DOM তৈরি করে। এই ভার্চুয়াল DOM ReactDOM দ্বারা ব্যাখ্যা করা হয় এবং HTMLElements রেন্ডার করে।
React-এ, Refs হলো মেমরিতে একটি জেনারেটেড HTMLElement ধারণ করার জন্য স্থান।
const RefsExample = (props) => {
const inputRef = React.useRef(null);
const onButtonClick = React.useCallback(() => {
inputRef.current?.focus();
}, [inputRef]);
return (
<div>
<input type={"text"} ref={inputRef} />
<br />
<button onClick={onButtonClick}>
Click to focus on the input above!
</button>
</div>
);
};
উপরের উদাহরণে, React কম্পোনেন্ট নিম্নলিখিত কাজগুলি করবে:
- একটি খালি টেক্সট ইনপুট এবং টেক্সট সহ একটি বোতাম রেন্ডার করুন
- বোতামটি ক্লিক করার সময় ইনপুটটি ফোকাস করুন
প্রাথমিক রেন্ডারের পরে, React ref অ্যাট্রিবিউটের মাধ্যমে জেনারেট করা HTMLInputElement এ inputRef.current সেট করবে।
@query সহ "রেফারেন্স" লিখুন
লিট ব্রাউজারের কাছাকাছি থাকে এবং নেটিভ ব্রাউজার বৈশিষ্ট্যগুলির উপর খুব পাতলা বিমূর্ততা তৈরি করে।
Lit-এ refs এর সমতুল্য React হল @query এবং @queryAll ডেকোরেটরদের দ্বারা ফেরত দেওয়া HTMLElement।
@customElement("my-element")
export class MyElement extends LitElement {
@query('input') // Define the query
inputEl!: HTMLInputElement; // Declare the prop
// Declare the click event listener
onButtonClick() {
// Use the query to focus
this.inputEl.focus();
}
render() {
return html`
<input type="text">
<br />
<!-- Bind the click listener -->
<button @click=${this.onButtonClick}>
Click to focus on the input above!
</button>
`;
}
}
উপরের উদাহরণে, Lit উপাদানটি নিম্নলিখিত কাজগুলি করে:
-
@queryডেকোরেটর ব্যবহার করেMyElementএ একটি প্রোপার্টি সংজ্ঞায়িত করে (একটিHTMLInputElementএর জন্য একটি গেটার তৈরি করে)। -
onButtonClickনামক একটি ক্লিক ইভেন্ট কলব্যাক ঘোষণা করে এবং সংযুক্ত করে। - বোতাম ক্লিকের ইনপুটকে ফোকাস করে
জাভাস্ক্রিপ্টে, @query এবং @queryAll ডেকোরেটর যথাক্রমে querySelector এবং querySelectorAll সঞ্চালন করে। এটি @query('input') inputEl!: HTMLInputElement;
get inputEl() {
return this.renderRoot.querySelector('input');
}
Lit কম্পোনেন্টটি render পদ্ধতির টেমপ্লেটটি my-element এর রুটে কমিট করার পর, @query ডেকোরেটর এখন inputEl রেন্ডার রুটে পাওয়া প্রথম input উপাদানটি ফেরত দেওয়ার অনুমতি দেবে। @query নির্দিষ্ট উপাদানটি খুঁজে না পেলে এটি null ফেরত দেবে।
যদি রেন্ডার রুটে একাধিক input উপাদান থাকে, তাহলে @queryAll নোডের একটি তালিকা ফেরত দেবে।
১০. মধ্যস্থতাকারী অবস্থা
এই বিভাগে, আপনি শিখবেন কিভাবে লিট-এ উপাদানগুলির মধ্যে অবস্থা নির্ধারণ করতে হয়।
পুনর্ব্যবহারযোগ্য উপাদান
রিঅ্যাক্ট টপ-ডাউন ডেটা ফ্লো সহ কার্যকরী রেন্ডারিং পাইপলাইনের অনুকরণ করে। অভিভাবকরা প্রপসের মাধ্যমে শিশুদের অবস্থা প্রদান করে। শিশুরা প্রপসে পাওয়া কলব্যাকের মাধ্যমে পিতামাতার সাথে যোগাযোগ করে।
const CounterButton = (props) => {
const label = props.step < 0
? `- ${-1 * props.step}`
: `+ ${props.step}`;
return (
<button
onClick={() =>
props.addToCounter(props.step)}>{label}</button>
);
};
উপরের উদাহরণে, একটি React উপাদান নিম্নলিখিত কাজগুলি করে:
-
props.stepমানের উপর ভিত্তি করে একটি লেবেল তৈরি করে। - +step অথবা -step লেবেল সহ একটি বোতাম রেন্ডার করে।
- ক্লিক করলে
props.stepকে আর্গুমেন্ট হিসেবে ব্যবহার করেprops.addToCounterকল করে প্যারেন্ট কম্পোনেন্ট আপডেট করা হয়।
যদিও Lit-এ কলব্যাক পাস করা সম্ভব, তবে প্রচলিত প্যাটার্নগুলি ভিন্ন। উপরের উদাহরণে React Component-কে নীচের উদাহরণে Lit Component হিসেবে লেখা যেতে পারে:
@customElement('counter-button')
export class CounterButton extends LitElement {
@property({type: Number}) step: number = 0;
onClick() {
const event = new CustomEvent('update-counter', {
bubbles: true,
detail: {
step: this.step,
}
});
this.dispatchEvent(event);
}
render() {
const label = this.step < 0
? `- ${-1 * this.step}` // "- 1"
: `+ ${this.step}`; // "+ 1"
return html`
<button @click=${this.onClick}>${label}</button>
`;
}
}
উপরের উদাহরণে, একটি Lit Component নিম্নলিখিত কাজগুলি করবে:
- প্রতিক্রিয়াশীল সম্পত্তি
stepতৈরি করুন - ক্লিক করলে এলিমেন্টের
stepভ্যালু বহন করেupdate-counterনামক একটি কাস্টম ইভেন্ট প্রেরণ করুন।
ব্রাউজার ইভেন্টগুলি শিশুদের থেকে প্যারেন্ট এলিমেন্টে বুদবুদ হয়ে ওঠে। ইভেন্টগুলি শিশুদের ইন্টারঅ্যাকশন ইভেন্ট এবং স্টেট পরিবর্তনগুলি সম্প্রচার করতে দেয়। React মূলত বিপরীত দিকে স্টেট প্রেরণ করে, তাই React Components Lit Components এর মতো একইভাবে ইভেন্টগুলি প্রেরণ এবং শোনা অস্বাভাবিক।
স্টেটফুল কম্পোনেন্টস
React-এ, অবস্থা পরিচালনা করার জন্য হুক ব্যবহার করা সাধারণ। CounterButton Component পুনঃব্যবহার করে একটি MyCounter Component তৈরি করা যেতে পারে। লক্ষ্য করুন কিভাবে addToCounter CounterButton এর উভয় ক্ষেত্রেই পাস করা হয়।
const MyCounter = (props) => {
const [counterSum, setCounterSum] = React.useState(0);
const addToCounter = useCallback(
(step) => {
setCounterSum(counterSum + step);
},
[counterSum, setCounterSum]
);
return (
<div>
<h3>Σ: {counterSum}</h3>
<CounterButton
step={-1}
addToCounter={addToCounter} />
<CounterButton
step={1}
addToCounter={addToCounter} />
</div>
);
};
উপরের উদাহরণটি নিম্নলিখিত কাজ করে:
- একটি
countঅবস্থা তৈরি করে। - একটি কলব্যাক তৈরি করে যা একটি
countঅবস্থায় একটি সংখ্যা যোগ করে। -
CounterButtonপ্রতিটি ক্লিকেরstepcountআপডেট করার জন্যaddToCounterব্যবহার করে।
MyCounter এর অনুরূপ বাস্তবায়ন লিট ভাষায়ও করা যেতে পারে। লক্ষ্য করুন কিভাবে addToCounter counter-button এ পাস করা হয় না। পরিবর্তে, কলব্যাকটি একটি প্যারেন্ট এলিমেন্টের @update-counter ইভেন্টের ইভেন্ট লিসেনার হিসেবে আবদ্ধ থাকে।
@customElement("my-counter")
export class MyCounter extends LitElement {
@property({type: Number}) count = 0;
addToCounter(e: CustomEvent<{step: number}>) {
// Get step from detail of event or via @query
this.count += e.detail.step;
}
render() {
return html`
<div @update-counter="${this.addToCounter}">
<h3>Σ ${this.count}</h3>
<counter-button step="-1"></counter-button>
<counter-button step="1"></counter-button>
</div>
`;
}
}
উপরের উদাহরণটি নিম্নলিখিত কাজ করে:
-
countনামক একটি প্রতিক্রিয়াশীল বৈশিষ্ট্য তৈরি করে যা মান পরিবর্তন করলে কম্পোনেন্টটি আপডেট করবে। -
addToCounterকলব্যাককে@update-counterইভেন্ট লিসেনারের সাথে আবদ্ধ করে। -
update-counterইভেন্টেরdetail.stepএ পাওয়া মান যোগ করে আপডেটcount। -
stepঅ্যাট্রিবিউটের মাধ্যমেcounter-buttonএরstepমান সেট করে।
পিতামাতা থেকে সন্তানদের মধ্যে পরিবর্তন সম্প্রচারের জন্য লিট-এ প্রতিক্রিয়াশীল বৈশিষ্ট্য ব্যবহার করা আরও প্রচলিত। একইভাবে, ব্রাউজারের ইভেন্ট সিস্টেম ব্যবহার করে নিচ থেকে উপরের দিকে বিস্তারিত বুদবুদ করা ভালো অভ্যাস।
এই পদ্ধতিটি সর্বোত্তম অনুশীলন অনুসরণ করে এবং ওয়েব উপাদানগুলির জন্য ক্রস-প্ল্যাটফর্ম সহায়তা প্রদানের লিটের লক্ষ্য মেনে চলে।
১১. স্টাইলিং
এই বিভাগে আপনি লিট ভাষায় স্টাইলিং সম্পর্কে শিখবেন।
স্টাইলিং
লিট উপাদানগুলিকে স্টাইল করার একাধিক উপায়ের পাশাপাশি একটি অন্তর্নির্মিত সমাধানও অফার করে।
ইনলাইন স্টাইল
Lit ইনলাইন স্টাইলের সাথে বাইন্ডিং সমর্থন করে।
import {LitElement, html, css} from 'lit';
import {customElement} from 'lit/decorators.js';
@customElement('my-element')
class MyElement extends LitElement {
render() {
return html`
<div>
<h1 style="color:orange;">This text is orange</h1>
<h1 style="color:rebeccapurple;">This text is rebeccapurple</h1>
</div>
`;
}
}
উপরের উদাহরণে ইনলাইন স্টাইল সহ ২টি করে শিরোনাম রয়েছে।
এবার border-color.js থেকে কমলা টেক্সটে একটি বর্ডার ইম্পোর্ট করুন এবং বাইন্ড করুন:
...
import borderColor from './border-color.js';
...
html`
...
<h1 style="color:orange;${borderColor}">This text is orange</h1>
...`
প্রতিবার স্টাইল স্ট্রিং গণনা করা কিছুটা বিরক্তিকর হতে পারে, তাই লিট এটিতে সহায়তা করার জন্য একটি নির্দেশিকা প্রদান করে।
স্টাইলম্যাপ
styleMap নির্দেশিকা জাভাস্ক্রিপ্ট ব্যবহার করে ইনলাইন স্টাইল সেট করা সহজ করে তোলে। উদাহরণস্বরূপ:
import {LitElement, html, css} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import {styleMap} from 'lit/directives/style-map.js';
@customElement('my-element')
class MyElement extends LitElement {
@property({type: String})
color = '#000'
render() {
// Define the styleMap
const headerStyle = styleMap({
'border-color': this.color,
});
return html`
<div>
<h1
style="border-style:solid;
<!-- Use the styleMap -->
border-width:2px;${headerStyle}">
This div has a border color of ${this.color}
</h1>
<input
type="color"
@input=${e => (this.color = e.target.value)}
value="#000">
</div>
`;
}
}
উপরের উদাহরণটি নিম্নলিখিত কাজ করে:
- বর্ডার এবং কালার পিকার সহ একটি
h1প্রদর্শন করে - কালার পিকার থেকে
border-colorমান পরিবর্তন করে।
অতিরিক্তভাবে, styleMap আছে যা h1 এর স্টাইল সেট করতে ব্যবহৃত হয়। styleMap React এর style attribute বাইন্ডিং সিনট্যাক্সের অনুরূপ একটি সিনট্যাক্স অনুসরণ করে।
CSSResult
কম্পোনেন্ট স্টাইল করার প্রস্তাবিত উপায় হল css ট্যাগযুক্ত টেমপ্লেট লিটারেল ব্যবহার করা।
import {LitElement, html, css} from 'lit';
import {customElement} from 'lit/decorators.js';
const ORANGE = css`orange`;
@customElement('my-element')
class MyElement extends LitElement {
static styles = [
css`
#orange {
color: ${ORANGE};
}
#purple {
color: rebeccapurple;
}
`
];
render() {
return html`
<div>
<h1 id="orange">This text is orange</h1>
<h1 id="purple">This text is rebeccapurple</h1>
</div>
`;
}
}
উপরের উদাহরণটি নিম্নলিখিত কাজ করে:
- একটি বাইন্ডিং সহ একটি CSS ট্যাগযুক্ত টেমপ্লেট লিটারেল ঘোষণা করে।
- দুটি
h1s এর আইডি সহ রঙ সেট করে।
css টেমপ্লেট ট্যাগ ব্যবহারের সুবিধা:
- প্রতি ক্লাস বনাম প্রতি উদাহরণে একবার বিশ্লেষণ করা হয়েছে
- মডিউল পুনঃব্যবহারযোগ্যতার কথা মাথায় রেখে বাস্তবায়িত
- সহজেই স্টাইলগুলিকে তাদের নিজস্ব ফাইলে আলাদা করতে পারে
- CSS কাস্টম প্রোপার্টিজ পলিফিলের সাথে সামঞ্জস্যপূর্ণ
অতিরিক্তভাবে, index.html এ <style> ট্যাগটি লক্ষ্য করুন:
<!-- index.html -->
<style>
h1 {
color: red !important;
}
</style>
Lit আপনার কম্পোনেন্টের স্টাইলগুলিকে তাদের মূলে বিস্তৃত করবে। এর অর্থ হল স্টাইলগুলি ভিতরে এবং বাইরে লিক হবে না। কম্পোনেন্টগুলিতে স্টাইলগুলি প্রেরণ করার জন্য, Lit টিম CSS কাস্টম প্রোপার্টি ব্যবহার করার পরামর্শ দেয় কারণ তারা Lit স্টাইল স্কোপিং ভেদ করতে পারে।
স্টাইল ট্যাগ
আপনার টেমপ্লেটগুলিতে কেবল <style> ট্যাগগুলি ইনলাইন করা সম্ভব। ব্রাউজার এই স্টাইল ট্যাগগুলিকে ডিডুপ্লিকেট করবে, তবে আপনার টেমপ্লেটগুলিতে এগুলি স্থাপন করলে, প্রতিটি ক্লাসের পরিবর্তে প্রতিটি উপাদানের উদাহরণ অনুসারে পার্স করা হবে, যেমনটি css ট্যাগযুক্ত টেমপ্লেটের ক্ষেত্রে হয়। অতিরিক্তভাবে, CSSResult s এর ব্রাউজার ডিডুপ্লিকেশন অনেক দ্রুত।
Link ট্যাগ
আপনার টেমপ্লেটে <link rel="stylesheet"> ব্যবহার করা স্টাইলের ক্ষেত্রেও সম্ভব, তবে এটিও সুপারিশ করা হয় না কারণ এটি প্রাথমিকভাবে আনস্টাইলড কন্টেন্ট (FOUC) এর ঝলকানি সৃষ্টি করতে পারে।
১২. উন্নত বিষয় (ঐচ্ছিক)
JSX & Templating
Lit & Virtual DOM
Lit-html does not include a conventional Virtual DOM that diffs each individual node. Instead it utilizes performance features intrinsic to ES2015's tagged template literal spec. Tagged template literals are template literal strings with tag functions attached to them.
Here is an example of a template literal:
const str = 'string';
console.log(`This is a template literal ${str}`);
Here is an example of a tagged template literal:
const tag = (strings, ...values) => ({strings, values});
const f = (x) => tag`hello ${x} how are you`;
console.log(f('world')); // {strings: ["hello ", " how are you"], values: ["world"]}
console.log(f('world').strings === f(1 + 2).strings); // true
In the above example, the tag is the tag function and the f function returns an invocation of a tagged template literal.
A lot of the performance magic in Lit comes from the fact that the string arrays passed into the tag function have the same pointer (as shown in the second console.log ). The browser does not recreate a new strings array on each tag function invocation, because it is using the same template literal (ie in the same location in the AST). So Lit's binding, parsing, and template caching can take advantage of these features without much runtime diffing overhead.
This built-in browser behavior of tagged template literals gives Lit quite a performance advantage. Most conventional Virtual DOMs do the majority of their work in JavaScript. However, tagged template literals do most of their diffing in the browser's C++.
If you'd like to get started using HTML tagged template literals with React or Preact, the Lit team recommends the htm library .
Though, as is the case with the Google Codelabs site and several online code editors, you will notice that tagged template literal syntax highlighting is not very common. Some IDEs and text editors support them by default such as Atom and GitHub's codeblock highlighter. The Lit team also works very closely with the community to maintain projects such as the lit-plugin which is a VS Code plugin that will add syntax highlighting, type checking, and intellisense to your Lit projects.
Lit & JSX + React DOM
JSX does not run in the browser and instead uses a preprocessor to convert JSX to JavaScript function calls (typically via Babel).
For example, Babel will transform this:
const element = <div className="title">Hello World!</div>;
ReactDOM.render(element, mountNode);
into this:
const element = React.createElement('div', {className: 'title'}, 'Hello World!');
ReactDOM.render(element, mountNode);
React DOM then takes the React output and translates it to actual DOM – properties, attributes, event listeners, and all.
Lit-html uses tagged template literals which can run in the browser without transpilation or a preprocessor. This means that in order to get started with Lit, all you need is an HTML file, an ES module script, and a server. Here's a completely browser-runnable script:
<!DOCTYPE html>
<html>
<head>
<script type="module">
import {html, render} from 'https://cdn.skypack.dev/lit';
render(
html`<div>Hello World!</div>`,
document.querySelector('.root')
)
</script>
</head>
<body>
<div class="root"></div>
</body>
</html>
Additionally, since Lit's templating system, lit-html, does not use a conventional Virtual DOM but rather uses the DOM API directly, Lit 2's size is under 5kb minified and gzipped compared to React (2.8kb) + react-dom's (39.4kb) 40kb minified and gizipped.
ইভেন্টগুলি
React uses a synthetic event system. This means that react-dom must define every event that will be used on every component and provide a camelCase event listener equivalent for each type of node. As a result, JSX does not have a method to define an event listener for a custom event and developers must use a ref and then imperatively apply a listener. This creates a sub-par developer experience when integrating libraries that don't have React in mind thus resulting in having to write a React-specific wrapper.
Lit-html directly accesses the DOM and uses native events, so adding event listeners is as easy as @event-name=${eventNameListener} . This means that less runtime parsing is done for adding event listeners as well as firing events.
Components & Props
React components & custom elements
Under the hood, LitElement uses custom elements to package its components. Custom elements introduce some tradeoffs between React components when it comes to componentization (state and lifecycle is discussed further in the State & Lifecycle section).
Some advantages Custom Elements have as a component system:
- Native to the browser and do not require any tooling
- Fit into every browser API from
innerHTMLanddocument.createElementtoquerySelector - Can typically be used across frameworks
- Can be lazily registered with
customElements.defineand "hydrate" DOM
Some disadvantages Custom Elements have compared to React components:
- Cannot create a custom element without defining a class (thus no JSX-like functional components)
- Must contain a closing tag
- Note: despite the developer convenience browser vendors tend to regret the self-closing tag spec which is why newer specs tend to not include self-closing tags
- Introduces an extra node to the DOM tree which may cause layout issues
- Must be registered via JavaScript
Lit has gone with custom elements over a bespoke element system because the custom elements are built into the browser, and the Lit team believes that the cross-framework benefits outweigh the benefits provided by a component abstraction layer. In fact, the Lit team's efforts in the lit-ssr space have overcome the main issues with JavaScript registration. Additionally, some companies such as GitHub take advantage of custom element lazy registration to progressively enhance pages with optional flair.
Passing data to custom elements
A common misconception with custom elements is that data can only be passed in as strings. This misconception likely comes from the fact that element attributes can only be written as strings. Though it is true that Lit will cast string attributes to their defined types, custom elements can also accept complex data as properties.
For example – given the following LitElement definition:
// data-test.ts
import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';
@customElement('data-test')
class DataTest extends LitElement {
@property({type: Number})
num = 0;
@property({attribute: false})
data = {a: 0, b: null, c: [html`<div>hello</div>`, html`<div>world</div>`]}
render() {
return html`
<div>num + 1 = ${this.num + 1}</div>
<div>data.a = ${this.data.a}</div>
<div>data.b = ${this.data.b}</div>
<div>data.c = ${this.data.c}</div>`;
}
}
A primitive reactive property num is defined which will convert an attribute's string value into a number , and then complex data structure is introduced with attribute:false which deactivates Lit's attribute handling.
This is how to pass data to this custom element:
<head>
<script type="module">
import './data-test.js'; // loads element definition
import {html} from './data-test.js';
const el = document.querySelector('data-test');
el.data = {
a: 5,
b: null,
c: [html`<div>foo</div>`,html`<div>bar</div>`]
};
</script>
</head>
<body>
<data-test num="5"></data-test>
</body>
State & Lifecycle
Other React Lifecycle Callbacks
static getDerivedStateFromProps
There is no equivalent in Lit as props and state are both the same class properties
shouldComponentUpdate
- Lit equivalent is
shouldUpdate - Called on first render unlike React
- Similar in function to React's
shouldComponentUpdate
getSnapshotBeforeUpdate
In Lit, getSnapshotBeforeUpdate is similar to both update and willUpdate
willUpdate
- Called before
update - Unlike
getSnapshotBeforeUpdate,willUpdateis called beforerender - Changes to reactive properties in
willUpdatedo not re-trigger the update cycle - Good place to compute property values that depend on other properties and are used in the rest of the update process
- This method is called on the server in SSR, so accessing the DOM is not advised here
update
- Called after
willUpdate - Unlike
getSnapshotBeforeUpdate,updateis called beforerender - Changes to reactive properties in
updatedo not re-trigger the update cycle if changed before callingsuper.update - Good place to capture information from the DOM surrounding the component before the rendered output is committed to the DOM
- This method is not called on the server in SSR
Other Lit Lifecycle Callbacks
There are several lifecycle callbacks that were not mentioned in the previous section because there is no analog to them in React. They are:
attributeChangedCallback
It is invoked when one of the element's observedAttributes changes. Both observedAttributes and attributeChangedCallback are part of the custom elements spec and implemented by Lit under the hood to provide an attribute API for Lit elements.
adoptedCallback
Invoked when the component is moved to a new document eg from an HTMLTemplateElement 's documentFragment to the main document . This callback is also a part of the custom elements spec and should only be used for advanced use cases when the component changes documents.
Other lifecycle methods and properties
These methods and properties are class members you can call, override, or await to help manipulate the lifecycle process.
updateComplete
This is a Promise that resolves when the element has finished updating as the update and render lifecycles are asynchronous. An example:
async nextButtonClicked() {
this.step++;
// Wait for the next "step" state to render
await this.updateComplete;
this.dispatchEvent(new Event('step-rendered'));
}
getUpdateComplete
This is a method that should be overridden to customize when updateComplete resolves. This is common when a component is rendering a child component and their render cycles must be in sync. eg,
class MyElement extends LitElement {
...
async getUpdateComplete() {
await super.getUpdateComplete();
await this.myChild.updateComplete;
}
}
performUpdate
This method is what calls the update lifecycle callbacks. This should generally not be needed except for rare cases where updating must be done synchronously or for custom scheduling.
hasUpdated
This property is true if the component has updated at least once.
isConnected
A part of the custom elements spec, this property will be true if the element is currently attached to the main document tree.
Lit Update Lifecycle Visualization
There are 3 parts to the update lifecycle:
- Pre-update
- আপডেট
- Post-update
Pre-Update

After requestUpdate , a scheduled update is awaited.
আপডেট

Post-Update

হুকস
Why hooks
Hooks were introduced into React for simple function component use cases that required state. In many simple cases function components with hooks tend to be much simpler and more readable than their class component counterparts. Though, when introducing asynchonous state updates as well as passing data between hooks or effects, the hooks pattern tends to not suffice, and a class-based solution like reactive controllers tend to shine.
API request hooks & controllers
It is common to write a hook that requests data from an API. For example, take this React function component that does the following:
-
index.tsx- Renders text
- Renders
useAPI's response- User ID + User name
- ত্রুটি বার্তা
- 404 when reaches user 11 (by design)
- Abort error if API fetch is aborted
- Loading Message
- Renders an action button
- Next user: which fetches the API for the next user
- Cancel: which aborts the API fetch and displays an error
-
useApi.tsx- Defines a
useApicustom hook - Will async fetch a user object from an api
- Emits:
- ব্যবহারকারীর নাম
- Whether the fetch is loading
- Any error messages
- A callback to abort the fetch
- Aborts fetches in progress if dismounted
- Defines a
Here is the Lit + Reactive Controller implementation .
টেকওয়ে:
- Reactive Controllers are most like custom hooks
- Passing non-renderable data between callbacks and effects
- React uses
useRefto pass data betweenuseEffectanduseCallback - Lit uses a private class property
- React is essentially mimicking the behavior of a private class property
- React uses
Additionally, if you really like the React function component syntax with hooks but the same buildless environment of Lit, the Lit team highly recommends the Haunted library.
শিশুরা
Default Slot
When HTML elements are not given a slot attribute, they are assigned to the default unnamed slot. In the example below, MyApp will slot one paragraph into a named slot. The other paragraph will default to the unnamed slot".
@customElement("my-element")
export class MyElement extends LitElement {
render() {
return html`
<section>
<div>
<slot></slot>
</div>
<div>
<slot name="custom-slot"></slot>
</div>
</section>
`;
}
}
@customElement("my-app")
export class MyApp extends LitElement {
render() {
return html`
<my-element>
<p slot="custom-slot">
This paragraph will be placed in the custom-slot!
</p>
<p>
This paragraph will be placed in the unnamed default slot!
</p>
</my-element>
`;
}
}
Slot Updates
When the structure of slot descendants change, a slotchange event is fired. A Lit component can bind an event-listener to a slotchange event. In the example below, the first slot found in the shadowRoot will have their assignedNodes logged to the console on slotchange .
@customElement("my-element")
export class MyElement extends LitElement {
onSlotChange(e: Event) {
const slot = this.shadowRoot.querySelector('slot');
console.log(slot.assignedNodes({flatten: true}));
}
render() {
return html`
<section>
<div>
<slot @slotchange="{this.onSlotChange}"></slot>
</div>
</section>
`;
}
}
রেফারেন্স
Reference generation
Lit and React both expose a reference to an HTMLElement after their render functions have been called. But it's worth reviewing how React and Lit compose the DOM that is later returned through a Lit @query decorator or a React Reference.
React is a functional pipeline that creates React Components not HTMLElements. Because a Ref is declared before an HTMLElement is rendered, a space in memory is allocated. This is why you see null as the initial value of a Ref, because the actual DOM element hasn't yet been created (or rendered) ie useRef(null) .
After ReactDOM converts a React Component into an HTMLElement, it looks for an attribute called ref in the ReactComponent. If available, ReactDOM places the HTMLElement's reference to ref.current .
LitElement uses the html template tag function from lit-html to compose a Template Element under the hood. LitElement stamps the template's contents to a custom element's shadow DOM after render. The shadow DOM is a scoped DOM tree encapsulated by a shadow root. The @query decorator then creates a getter for the property which essentially performs a this.shadowRoot.querySelector on the scoped root.
Query Multiple Elements
In the example below, the @queryAll decorator will return the two paragraphs in the shadow root as a NodeList .
@customElement("my-element")
export class MyElement extends LitElement {
@queryAll('p')
paragraphs!: NodeList;
render() {
return html`
<p>Hello, world!</p>
<p>How are you?</p>
`;
}
}
Essentially, @queryAll creates a getter for paragraphs that returns the results of this.shadowRoot.querySelectorAll() . In JavaScript, a getter can be declared to perform the same purpose:
get paragraphs() {
return this.renderRoot.querySelectorAll('p');
}
Query Changing Elements
The @queryAsync decorator is better suited to handle a node that can change based on the state of another element property.
In the example below, @queryAsync will find the first paragraph element. However, a paragraph element will only be rendered when renderParagraph randomly generates an odd number. The @queryAsync directive will return a promise that will resolve when the first paragraph is available.
@customElement("my-dissappearing-paragraph")
export class MyDisapppearingParagraph extends LitElement {
@queryAsync('p')
paragraph!: Promise<HTMLElement>;
renderParagraph() {
const randomNumber = Math.floor(Math.random() * 10)
if (randomNumber % 2 === 0) {
return "";
}
return html`<p>This checkbox is checked!`
}
render() {
return html`
${this.renderParagraph()}
`;
}
}
Mediating State
In React, convention is to use callbacks because state is mediated by React itself. React does it's best to not rely on state provided by elements. The DOM is simply an effect of the rendering process.
External State
It's possible to use Redux, MobX, or any other state management library alongside Lit.
Lit components are created in browser scope. So any library that also exists in browser scope is available to Lit. Many amazing libraries have been built to utilize existing state management systems in Lit.
Here is a series by Vaadin explaining how to leverage Redux in a Lit component.
Take a look at lit-mobx from Adobe to see how a large scale site can leverage MobX in Lit.
Also, check out Apollo Elements to see how developers are including GraphQL in their web components.
Lit works with native browser features and most state management solutions in browser scope can be used in a Lit component.
স্টাইলিং
Shadow DOM
To natively encapsulate styles and DOM within a Custom Element, Lit uses Shadow DOM . Shadow Roots generate a shadow tree separate from the main document tree. This means that most styles are scoped to this document. Certain styles do leak through such as color, and other font-related styles.
Shadow DOM also introduces new concepts and selectors to the CSS spec:
:host, :host(:hover), :host([hover]) {
/* Styles the element in which the shadow root is attached to */
}
slot[name="title"]::slotted(*), slot::slotted(:hover), slot::slotted([hover]) {
/*
* Styles the elements projected into a slot element. NOTE: the spec only allows
* styling the direcly slotted elements. Children of those elements are not stylable.
*/
}
Sharing Styles
Lit makes it easy to share styles between components in the form of CSSTemplateResults via css template tags. For example:
// typography.ts
export const body1 = css`
.body1 {
...
}
`;
// my-el.ts
import {body1} from './typography.ts';
@customElement('my-el')
class MyEl Extends {
static get styles = [
body1,
css`/* local styles come after so they will override bod1 */`
]
render() {
return html`<div class="body1">...</div>`
}
}
থিমিং
Shadow roots present a bit of a challenge to conventional theming which typically are top-down style tag approaches. The conventional way to tackle theming with Web Components that use Shadow DOM is to expose a style API via CSS Custom Properties . For example, this is a pattern that Material Design uses:
.mdc-textfield-outline {
border-color: var(--mdc-theme-primary, /* default value */ #...);
}
.mdc-textfield--input {
caret-color: var(--mdc-theme-primary, #...);
}
The user would then change the theme of the site by applying custom property values:
html {
--mdc-theme-primary: #F00;
}
html[dark] {
--mdc-theme-primary: #F88;
}
If top-down theming is a must and you are unable to expose styles, it is always possible to disable Shadow DOM by overriding createRenderRoot to return this which will then render your components' template to the custom element itself rather than to a shadow root attached to the custom element. With this you will lose: style encapsulation, DOM encapsulation, and slots.
উৎপাদন
IE 11
If you need to support older browsers like IE 11, you will have to load some polyfills which come out to about another 33kb. More information can be found here .
Conditional Bundles
The Lit team recommends serving two different bundles, one for IE 11 and one for modern browsers. There are several benefits to this:
- Serving ES 6 is faster and will serve most of your clients
- Transpiled ES 5 significantly increases bundle size
- Conditional bundles give you the best of both worlds
- IE 11 support
- No slowdown on modern browsers
More info on how to build a conditionally served bundle can be found on our documentation site here .