投稿時間:2023-06-27 18:27:40 RSSフィード2023-06-27 18:00 分まとめ(38件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… Google初の折りたたみ式スマホ「Pixel Fold」、使用開始4日で壊れたとの事例が報告される ー ディスプレイの耐久性に不安が https://taisy0.com/2023/06/27/173409.html google 2023-06-27 08:55:27
IT ITmedia 総合記事一覧 [ITmedia News] Gatebox、AIキャラクター派遣サービス「AIバイト」と大型画面の専用端末を発表 ChatGPTと連携して接客も https://www.itmedia.co.jp/news/articles/2306/27/news158.html chatgpt 2023-06-27 17:37:00
python Pythonタグが付けられた新着投稿 - Qiita (メモ)並行処理の流れをサンプルで勉強する https://qiita.com/MasatoEmata/items/43eb4172c16dbe885bd5 eadpoolexecutormaxworkers 2023-06-27 17:38:52
技術ブログ Developers.IO 「クラスメソッドxアノテーションxネクストモード 3社合同Notion交流会 #1 」を開催しました。 #notion https://dev.classmethod.jp/articles/cm-an-nm-notion-gathering-1st/ notion 2023-06-27 08:49:34
技術ブログ Developers.IO 【レポート】Designer & Alteryx Analytics Cloud Platform: A Lovestory – Alteryx Inspire 2023 https://dev.classmethod.jp/articles/alteryx-inspire-2023-designer-and-cloud-lovestory/ alter 2023-06-27 08:22:27
技術ブログ Developers.IO Amazon CloudWatch Internet Monitorのスタック更新が今までと少し違った https://dev.classmethod.jp/articles/202306-cloudwatch-internet-monitor-cloudformation-stackupdate-01/ amazon 2023-06-27 08:10:09
海外TECH MakeUseOf 5 Novel RSS Reader Apps to Change How You Get News Feeds and Updates https://www.makeuseof.com/rss-reader-apps-news-feeds/ Novel RSS Reader Apps to Change How You Get News Feeds and UpdatesFrom AI summaries and ChatGPT queries of your RSS feeds to minimalist and privacy friendly apps you need to check out these cool new RSS readers 2023-06-27 08:31:18
海外TECH DEV Community 3 Examples of Brilliant Vertical Timelines with Tailwind CSS https://dev.to/cruip_com/3-examples-of-brilliant-vertical-timelines-with-tailwind-css-44 Examples of Brilliant Vertical Timelines with Tailwind CSS Live Demo Download A vertical timeline is an intelligent way to display a flow of information that branches out from top to bottom and involves some form of content connection e g temporal semantic etc From a purely technical standpoint a vertical timeline doesn t differ much from the more common horizontal timeline and the substantial difference lies in how the information is displayed a horizontal timeline is more suitable for “temporal content e g a calendar while a vertical timeline is ideal for related information In this tutorial we will show you how to create three distinct versions of vertical timelines using Tailwind CSS Specifically A milestone timeline A progress timeline A discussion notification timelineIf you want to take a look at how we previously implemented a vertical timeline in one of our Tailwind CSS templates we suggest checking out this SaaS website template called Open Pro Example The Milestone TimelineIn this example we will create a vertical timeline to display the milestones of a project using Tailwind CSS A milestone chart is a diagram that shows a series of important events or stages in a project represented by a vertical line that crosses the chart at the date they occur Let s begin by creating a simple HTML document where we can include the code for our timeline lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset utf gt lt title gt Vertical Timelines lt title gt lt meta name viewport content width device width initial scale gt lt link rel preconnect href gt lt link rel preconnect href crossorigin gt lt link href wght amp Caveat wght amp display swap rel stylesheet gt lt script src gt lt script gt lt script gt tailwind config theme extend fontFamily inter Inter sans serif caveat Caveat cursive lt script gt lt head gt lt body class relative font inter antialiased gt lt main class relative min h screen flex flex col justify center bg slate overflow hidden gt lt div class w full max w xl mx auto px md px py gt lt div class flex flex col justify center divide y divide slate amp gt py gt lt div class w full max w xl mx auto gt lt Vertical Timeline gt lt div gt lt div gt lt div gt lt main gt lt body gt lt html gt Now let s move on to designing our timeline During this phase it is crucial to have in mind how the timeline should appear on both mobile and desktop screens On desktop screens where there is more space available the date circle marker and title are aligned horizontally However on mobile devices we need to adjust the layout to ensure a better user experience In this case the title is positioned below the date and the circle marker To create the vertical line we will utilize the before pseudo element within each timeline element This approach gives us control over the height of the line and allows us to choose whether or not to display the vertical line on the last element of the timeline With these key design points in mind we can proceed to the next step constructing the timeline structure The structure will be organized as follows Timeline element should have left top and bottom padding Purple labelCircle marker before Date Title Vertical line after ContentLet s write the HTML code using Tailwind CSS utility classes Since each timeline element has a vertical padding of px defined by the py class we will apply a negative vertical margin of px to the container element using the my class to offset the padding lt Container gt lt div class my gt lt Timeline Item gt lt div class relative pl sm pl py group gt lt Purple label gt lt Vertical line before Date Title Circle marker after gt lt Content gt lt div gt lt div gt Now we can proceed with coding the timeline element lt Container gt lt div class my gt lt Timeline Item gt lt div class relative pl sm pl py group gt lt Purple label gt lt div class font caveat font medium text xl text indigo mb sm mb gt The origin lt div gt lt Vertical line before Date Title Circle marker after gt lt div class flex flex col sm flex row items start mb group last before hidden before absolute before left sm before left before h full before px px before bg slate sm before ml rem before self start before translate x before translate y after absolute after left sm after left after w after h after bg indigo after border after box content after border slate after rounded full sm after ml rem after translate x after translate y gt lt time class sm absolute left translate y inline flex items center justify center text xs font semibold uppercase w h mb sm mb text emerald bg emerald rounded full gt May lt time gt lt div class text xl font bold text slate gt Acme was founded in Milan Italy lt div gt lt div gt lt Content gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra pharetra massa massa Adipiscing enim eu neque aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt While the purple label and content require no futher explanations it is worth delving deeper into the central part Let s examine in detail the most significant classes we ve used The classes flex and flex col make the content inside the div arrange in columns Adding sm flex row ensures that on larger screens the date and title are positioned on the same row The lt time gt element is absolutely positioned on the left when the window width is greater than px thanks to the sm prefix sm absolute It is also moved rem down to align it vertically with the circle marker and the title sm translate y Additionally we ve set a fixed width of pixels w for this element to ensure proper alignment of the content on the right Keep in mind that if you decide to change the width you may need to adjust other related measurements in this example The vertical line is created using the pseudo element before with the before prefix It is absolutely positioned in relation to the timeline element before absolute The line extends vertically to cover the entire height of the timeline before h full and it starts from the circle marker visually connecting the timeline elements Furthermore we hide the segment of the last element by applying the group last before hidden class The circle marker is created using the pseudo element after using the after prefix It is absolutely positioned on the left side of the timeline element To achieve the desired positioning we fine tune its placement using the margin and transform properties The dimensions of the circle marker are set to × pixels after w after h and it features a px border after border that matches the page background after border slate As long as we have only one element in the timeline we won t see any vertical line Let s add the more items to see the connected circle markers along the line Here s the complete code lt div class my gt lt Item gt lt div class relative pl sm pl py group gt lt Purple label gt lt div class font caveat font medium text xl text indigo mb sm mb gt The origin lt div gt lt Vertical line before Date Title Circle marker after gt lt div class flex flex col sm flex row items start mb group last before hidden before absolute before left sm before left before h full before px px before bg slate sm before ml rem before self start before translate x before translate y after absolute after left sm after left after w after h after bg indigo after border after box content after border slate after rounded full sm after ml rem after translate x after translate y gt lt time class sm absolute left translate y inline flex items center justify center text xs font semibold uppercase w h mb sm mb text emerald bg emerald rounded full gt May lt time gt lt div class text xl font bold text slate gt Acme was founded in Milan Italy lt div gt lt div gt lt Content gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra pharetra massa massa Adipiscing enim eu neque aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt Item gt lt div class relative pl sm pl py group gt lt Purple label gt lt div class font caveat font medium text xl text indigo mb sm mb gt The milestone lt div gt lt Vertical line before Date Title Circle marker after gt lt div class flex flex col sm flex row items start mb group last before hidden before absolute before left sm before left before h full before px px before bg slate sm before ml rem before self start before translate x before translate y after absolute after left sm after left after w after h after bg indigo after border after box content after border slate after rounded full sm after ml rem after translate x after translate y gt lt time class sm absolute left translate y inline flex items center justify center text xs font semibold uppercase w h mb sm mb text emerald bg emerald rounded full gt May lt time gt lt div class text xl font bold text slate gt Reached K customers lt div gt lt div gt lt Content gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra pharetra massa massa Adipiscing enim eu neque aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt Item gt lt div class relative pl sm pl py group gt lt Purple label gt lt div class font caveat font medium text xl text indigo mb sm mb gt The acquisitions lt div gt lt Vertical line before Date Title Circle marker after gt lt div class flex flex col sm flex row items start mb group last before hidden before absolute before left sm before left before h full before px px before bg slate sm before ml rem before self start before translate x before translate y after absolute after left sm after left after w after h after bg indigo after border after box content after border slate after rounded full sm after ml rem after translate x after translate y gt lt time class sm absolute left translate y inline flex items center justify center text xs font semibold uppercase w h mb sm mb text emerald bg emerald rounded full gt May lt time gt lt div class text xl font bold text slate gt Acquired various companies inluding Technology Inc lt div gt lt div gt lt Content gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra pharetra massa massa Adipiscing enim eu neque aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt Item gt lt div class relative pl sm pl py group gt lt Purple label gt lt div class font caveat font medium text xl text indigo mb sm mb gt The IPO lt div gt lt Vertical line before Date Title Circle marker after gt lt div class flex flex col sm flex row items start mb group last before hidden before absolute before left sm before left before h full before px px before bg slate sm before ml rem before self start before translate x before translate y after absolute after left sm after left after w after h after bg indigo after border after box content after border slate after rounded full sm after ml rem after translate x after translate y gt lt time class sm absolute left translate y inline flex items center justify center text xs font semibold uppercase w h mb sm mb text emerald bg emerald rounded full gt May lt time gt lt div class text xl font bold text slate gt Acme went public at the New York Stock Exchange lt div gt lt div gt lt Content gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra pharetra massa massa Adipiscing enim eu neque aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt Example The Progress TimelineIn this second example we will show you how to create a progress timeline that visually represents the status of a something For example an e commerce order just like the example below We will follow a similar approach to the previous example We will first determine how the timeline should look on both mobile and desktop screens and then proceed with its implementation accordingly This pre planning ensures that the timeline is optimized for different devices and provides a consistent user experience across platforms Due to limited horizontal space on mobile screens we will position all the timeline elements to the right of the vertical line Unlike the previous example we will define the vertical line as a single element that extends across the entire height of the timeline Instead of dividing it into segments for each timeline element we will apply the before pseudo element at the container div level of the timeline lt Container gt lt div class space y relative before absolute before inset before ml before translate x px md before mx auto md before translate x before h full before w before bg gradient to b before from transparent before via slate before to transparent gt lt Timeline Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group is active gt lt Icon gt lt Card gt lt div gt lt div gt The vertical line is absolutely positioned within the timeline container The before h full class ensures that the line visually spans the entire timeline Additionally we have added a linear gradient that transitions from transparent to the color slate With the vertical line in place we can now proceed with defining the individual elements of the timeline each representing a specific oreder step lt Container gt lt div class space y relative before absolute before inset before ml before translate x px md before mx auto md before translate x before h full before w before bg gradient to b before from transparent before via slate before to transparent gt lt Timeline Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group is active gt lt Icon gt lt div class flex items center justify center w h rounded full border border white bg slate group is active bg emerald text slate group is active text emerald shadow shrink md order md group odd translate x md group even translate x gt lt svg class fill current xmlns width height gt lt path fill rule nonzero d M A l a l a Z gt lt svg gt lt div gt lt Card gt lt div class w calc rem md w calc rem bg white p rounded border border slate shadow gt lt div class flex items center justify between space x mb gt lt div class font bold text slate gt Order Placed lt div gt lt time class font caveat font medium text indigo gt lt time gt lt div gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt lt div gt We have an icon whose size is × pixels w h positioned next to a card varies based on the screen size On mobile screens the card occupies of the available width excluding a rem margin w calc rem On desktop screens the card occupies of the available width excluding a rem margin md w calc rem To ensure a consistent layout we utilize the flexbox model on mobile screens applying the justify between class to distribute the child elements with space between them On desktop screens we restore the natural order of elements using the md justify normal class and reverse the order in which they are displayed using md odd flex row reverse These classes create the alternating effect of the timeline elements Additionally we apply the classes md order md group odd translate x and md group even translate x to correctly reposition the icon Finally we have created an arbitrary group class called is active that allows us to apply a different style to the completed timeline elements When the is active class is applied to a timeline element the icon appears green otherwise it appears gray Here s the complete code for the second example lt div class space y relative before absolute before inset before ml before translate x px md before mx auto md before translate x before h full before w before bg gradient to b before from transparent before via slate before to transparent gt lt Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group is active gt lt Icon gt lt div class flex items center justify center w h rounded full border border white bg slate group is active bg emerald text slate group is active text emerald shadow shrink md order md group odd translate x md group even translate x gt lt svg class fill current xmlns width height gt lt path fill rule nonzero d M A l a l a Z gt lt svg gt lt div gt lt Card gt lt div class w calc rem md w calc rem bg white p rounded border border slate shadow gt lt div class flex items center justify between space x mb gt lt div class font bold text slate gt Order Placed lt div gt lt time class font caveat font medium text indigo gt lt time gt lt div gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt lt Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group is active gt lt Icon gt lt div class flex items center justify center w h rounded full border border white bg slate group is active bg emerald text slate group is active text emerald shadow shrink md order md group odd translate x md group even translate x gt lt svg class fill current xmlns width height gt lt path fill rule nonzero d M A l a l a Z gt lt svg gt lt div gt lt Card gt lt div class w calc rem md w calc rem bg white p rounded border border slate shadow gt lt div class flex items center justify between space x mb gt lt div class font bold text slate gt Order Shipped lt div gt lt time class font caveat font medium text indigo gt lt time gt lt div gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt lt Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group is active gt lt Icon gt lt div class flex items center justify center w h rounded full border border white bg slate group is active bg emerald text slate group is active text emerald shadow shrink md order md group odd translate x md group even translate x gt lt svg class fill current xmlns width height gt lt path fill rule nonzero d M A l a l a Z gt lt svg gt lt div gt lt Card gt lt div class w calc rem md w calc rem bg white p rounded border border slate shadow gt lt div class flex items center justify between space x mb gt lt div class font bold text slate gt In Transit lt div gt lt time class font caveat font medium text indigo gt lt time gt lt div gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt lt Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group is active gt lt Icon gt lt div class flex items center justify center w h rounded full border border white bg slate group is active bg emerald text slate group is active text emerald shadow shrink md order md group odd translate x md group even translate x gt lt svg class fill current xmlns width height gt lt path fill rule nonzero d M A l a l a Z gt lt svg gt lt div gt lt Card gt lt div class w calc rem md w calc rem bg white p rounded border border slate shadow gt lt div class flex items center justify between space x mb gt lt div class font bold text slate gt Out of Delivery lt div gt lt time class font caveat font medium text indigo gt lt time gt lt div gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt lt Item gt lt div class relative flex items center justify between md justify normal md odd flex row reverse group gt lt Icon gt lt div class flex items center justify center w h rounded full border border white bg slate group is active bg emerald text slate group is active text emerald shadow shrink md order md group odd translate x md group even translate x gt lt svg class fill current xmlns width height gt lt path d M vHVa h a VHVa l a l a VZ gt lt svg gt lt div gt lt Card gt lt div class w calc rem md w calc rem bg white p rounded border border slate shadow gt lt div class flex items center justify between space x mb gt lt div class font bold text slate gt Delivered lt div gt lt time class font caveat font medium text amber gt Exp lt time gt lt div gt lt div class text slate gt Pretium lectus quam id leo Urna et pharetra aliquam vestibulum morbi blandit cursus risus lt div gt lt div gt lt div gt lt div gt Example The Discussion TimelineNow we want to show you how to create a timeline of comments that can be applied to many different types of apps This timeline is structurally similar to the first example and visually similar to the second one So we will draw inspiration from the first example to ensure optimal display on both mobile and desktop screens and from the second example to create the vertical line with icons To begin let s focus on the container element lt Container gt lt div class space y relative before absolute before inset before ml before translate x px md before ml rem md before translate x before h full before w before bg gradient to b before from transparent before via slate before to transparent gt lt Timeline item gt lt div class relative gt lt Date Icon Title gt lt div gt lt div gt lt Icon gt lt Date gt lt div gt lt Title gt lt div gt lt Card gt lt div gt lt div gt As you can see we have reused a significant portion of the code from the previous example to create the vertical line using the before pseudo element However the structure of each timeline item is slightly more complex but the underlying approach remains similar to example We arrange the date icon and title on the same line followed by the content of the comment below On mobile screens we display the icon with the date and the title on a new line Let s examine how the code for a single timeline item is made lt Container gt lt div class space y relative before absolute before inset before ml before translate x px md before ml rem md before translate x before h full before w before bg gradient to b before from transparent before via slate before to transparent gt lt Timeline item gt lt div class relative gt lt div class md flex items center md space x mb gt lt div class flex items center space x md space x md space x reverse gt lt Icon gt lt div class flex items center justify center w h rounded full bg white shadow md order gt lt svg class fill emerald xmlns width height gt lt path d M a Zm a Z gt lt svg gt lt div gt lt Date gt lt time class font caveat font medium text xl text indigo md w gt Apr lt time gt lt div gt lt Title gt lt div class text slate ml gt lt span class text slate font bold gt Mark Mikrol lt span gt opened the request lt div gt lt div gt lt Card gt lt div class bg white p rounded border border slate text slate shadow ml md ml gt Various versions have evolved over the years sometimes by accident sometimes on purpose injected humour and the like lt div gt lt div gt lt div gt L unica novitàdegna di nota in questo layout riguarda il card element a cui abbiamo applicato un margine sinistro di px md ml per assicurarci che sia perfettamente allineata al title su desktop screens Ed ecco la timeline completa lt div class space y relative before absolute before inset before ml before translate x px md before ml rem md before translate x before h full before w before bg gradient to b before from transparent before via slate before to transparent gt lt Item gt lt div class relative gt lt div class md flex items center md space x mb gt lt div class flex items center space x md space x md space x reverse gt lt Icon gt lt div class flex items center justify center w h rounded full bg white shadow md order gt lt svg class fill emerald xmlns width height gt lt path d M a Zm a Z gt lt svg gt lt div gt lt Date gt lt time class font caveat font medium text xl text indigo md w gt Apr lt time gt lt div gt lt Title gt lt div class text slate ml gt lt span class text slate font bold gt Mark Mikrol lt span gt opened the request lt div gt lt div gt lt Card gt lt div class bg white p rounded border border slate text slate shadow ml md ml gt Various versions have evolved over the years sometimes by accident sometimes on purpose injected humour and the like lt div gt lt div gt lt Item gt lt div class relative gt lt div class md flex items center md space x mb gt lt div class flex items center space x md space x md space x reverse gt lt Icon gt lt div class flex items center justify center w h rounded full bg white shadow md order gt lt svg xmlns width height gt lt path class fill slate d M C c C c L a v c Z gt lt path class fill slate d M C c Va l c S Z gt lt svg gt lt div gt lt Date gt lt time class font caveat font medium text xl text indigo md w gt Apr lt time gt lt div gt lt Title gt lt div class text slate ml gt lt span class text slate font bold gt John Mirkovic lt span gt commented the request lt div gt lt div gt lt Card gt lt div class bg white p rounded border border slate text slate shadow ml md ml gt If you are going to use a passage of Lorem Ipsum you need to be sure there isn t anything embarrassing hidden in the middle of text lt div gt lt div gt lt Item gt lt div class relative gt lt div class md flex items center md space x mb gt lt div class flex items center space x md space x md space x reverse gt lt Icon gt lt div class flex items center justify center w h rounded full bg white shadow md order gt lt svg xmlns width height gt lt path class fill slate d M C c C c L a v c Z gt lt path class fill slate d M C c Va l c S Z gt lt svg gt lt div gt lt Date gt lt time class font caveat font medium text xl text indigo md w gt Apr lt time gt lt div gt lt Title gt lt div class text slate ml gt lt span class text slate font bold gt Vlad Patterson lt span gt commented the request lt div gt lt div gt lt Card gt lt div class bg white p rounded border border slate text slate shadow ml md ml gt Letraset sheets containing passages and more recently with desktop publishing software like Aldus PageMaker including versions of Ipsum lt div gt lt div gt lt Item gt lt div class relative gt lt div class md flex items center md space x mb gt lt div class flex items center space x md space x md space x reverse gt lt Icon gt lt div class flex items center justify center w h rounded full bg white shadow md order gt lt svg xmlns width height gt lt path class fill slate d M C c C c L a v c Z gt lt path class fill slate d M C c Va l c S Z gt lt svg gt lt div gt lt Date gt lt time class font caveat font medium text xl text indigo md w gt Apr lt time gt lt div gt lt Title gt lt div class text slate ml gt lt span class text slate font bold gt Mila Capentino lt span gt commented the request lt div gt lt div gt lt Card gt lt div class bg white p rounded border border slate text slate shadow ml md ml gt It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout lt div gt lt div gt lt Item gt lt div class relative gt lt div class md flex items center md space x mb gt lt div class flex items center space x md space x md space x reverse gt lt Icon gt lt div class flex items center justify center w h rounded full bg white shadow md order gt lt svg class fill red xmlns width height gt lt path d M a Zm a Z gt lt svg gt lt div gt lt Date gt lt time class font caveat font medium text xl text indigo md w gt Apr lt time gt lt div gt lt Title gt lt div class text slate ml gt lt span class text slate font bold gt Mark Mikrol lt span gt closed the request lt div gt lt div gt lt Card gt lt div class bg white p rounded border border slate text slate shadow ml md ml gt If you are going to use a passage of Lorem Ipsum lt div gt lt div gt lt div gt Final ThoughtsIf you have followed this tutorial from start to finish you have likely realized that creating a vertical timeline with Tailwind CSS is not a challenging task although it may require some time and effort We understand the importance of time in our work so we have provided pre built Next js and Vue components that you can easily incorporate into your projects We also encourage you to explore other tutorials in this series and browse through our collection of Tailwind CSS templates We are confident that you will discover a wealth of valuable resources for your upcoming projects 2023-06-27 08:26:52
海外TECH DEV Community How To Create Custom Hooks in React / Next JS https://dev.to/inaju/how-to-create-custom-hooks-in-react-next-js-46m5 How To Create Custom Hooks in React Next JS What are React Hooks React Hooks allows developers hook into React s lifecycle and state management features from functional components They provide a more concise and reusable way to manage component logic Some popular examples are useState and useEffect Hooks PrerequisitesGood understanding of react js hooks like useState and useEffect You have a react project running that you want to create a custom hook for Why should we use custom hooks React Hooks helps us to reuse logic across our code base You ve written a piece of Code that you later found out other files that might need that logic a good practice is to abstract that logic into a custom hook For example you ve written a functionality that allows you to communicate with an API this logic includes returning errors returning the success messages and sending data to the API It s always a good practice to abstract this logic into a hook so you can reuse it across your codebase so that you don t have to rewrite it in every file you need that logic This helps to make your code more organized and less bulky with repeated logic One clean Code principle is DRY ie Do not Repeat Yourself which means if a code is used multiple times across a file you turn it into a single code block or into a file and export it from that file to be used across your application Here are some rules you need to take note of when creating custom hooksNever call Hooks inside loops conditions or nested functions Always use Hooks at the top level of your React component Never call Hooks from regular JavaScript functions Instead call Hooks from React functional components or call Hooks from custom Hooks Make use of the use prefix to name your functions and the filename eg useEffect useState useFetch What are we going to do We re going to utilize JSON Placeholder Fake Data API to fetch dummy data that we are going to use for our application When interacting with an API we would need a library to interact with that API for that we are going to use Axios for this To install Axios When using NPM run this command on your terminal npm install axiosWhen using Yarn run this command on your terminal yarn add axiosCreate a Home js file on your react app and paste the code below Home jsimport useState useEffect from react import axios from axios const Home gt const data setData useState null const isLoading setIsLoading useState null const error setError useState null useEffect gt handleGetData const handleGetData async gt setIsLoading true try const getData await axios get if getData status setData getData data setIsLoading false catch error setError error throw console error error return lt gt isLoading amp amp lt p gt Loading lt p gt error amp amp lt div gt There was an Error lt button onClick handleGetData gt Try Again lt button gt lt div gt data amp amp isLoading amp amp data map item gt return lt p key item id gt item title lt p gt lt gt export default Home you should see this on the web pageThis Home js File does basic thingsFetching the data from JSON Placeholder API Set that response data to a state and a loading stateCatches any error on the file and sets it to an error state Displays if there was an error getting the data for the user to see Shows the loading state for the user to see Displays the Data for the user to seeThis is the basic functionality for pages that query an API hence the need for us to abstract this logic On a typical API you would have different endpoints like createAccount or getUser and to implement it you ll have to rewrite this logic for all files So let s abstract this into a reusable logic On the JSON Placeholder API we have access to these routes so it would make sense for us to allow our custom hook to accept any suffix link posts posts comments comments albums albums photos photos todos todos users users Step Identify the Code to be reused It s good practice to put files that are performing similar logic into the same folder you should have a hooks folder to hold all the custom hooks you ll create for your project So create a hooks folder and a file called useRequest jsYour directory should look something like this src hooks useRequest jsLet s copy the necessary re useable logic from our index js file into our useRequest js file which should look like this useRequest jsimport useState from react import axios from axios const useRequest gt const data setData useState null const isLoading setIsLoading useState null const error setError useState null const handleGetData async gt setIsLoading true try const getData await axios get if getData status setData getData data setIsLoading false catch error setError error throw console error error return data isLoading error handleGetData export default useRequest Explanation of the code const data setData useState null const isLoading setIsLoading useState null const error setError useState null These are the states that would handle the response from the API the loading state and the error state const handleGetData async gt setIsLoading true try const getData await axios get if getData status setData getData data setIsLoading false else setError There was an error catch error setError error throw console error error handleGetData is an async function here s what it does It first sets the loading state to true because we want to show a loading state while our hook is calling the endpoint We re wrapping the main logic in a try catch block because we want to handle the errors we might get errors such as network errors a request timeout or a data not found error The next line calls the API with axios checks if the status is ie there was a response with data and sets the data and loading state to false if the error state is not it means there was an error so we handle that return data isLoading error handleGetData The return statement is important because you might not always want to make all the functions or variables accessible on your hook so the return allows us to specify what we want to expose Here we are exposing the response of our API call data loading and error states and handleGetData function which we explained earlier Step How to use itSince we re done abstracting the reusable functionality into a hook here s how to use it const data isLoading error handleGetData useRequest Just looking at this you ll see that it s pretty similar to how you ll use the basic react hooks like useState or useEffect Here s how our Home js file now looks Home jsimport useState useEffect from react import useRequest from hooks useRequest const Home gt const data isLoading error handleGetData useRequest useEffect gt handleGetData return lt div gt isLoading amp amp lt p gt Loading lt p gt error amp amp lt div gt There was an Error lt button onClick handleGetData gt Try Again lt button gt lt div gt data amp amp isLoading amp amp data map item gt return lt p key item id gt item title lt p gt lt div gt export default Home We can see that we ve reduced the code to virtually under lines of code for us which is a good thing we ve abstracted the logic for calling the API into a custom hook that we are going to make more re useable now If you ve read to this point you already know the basics of creating custom hooks in React what we are going to do in the next section is to make the hook accept any endpoint and base API link Step Make the hook more reusable What we are going to do here is to allow our useRequest js function to accept two arguments ie BASE API and suffix Our BASE API is the most common url we can find on all our endpoints The suffix is the different endpoints For example BASE API www simpleapi com suffix posts so together the full URL would look like www simpleapi com posts Here are the changes we would be making to our useRequest jsIn your Home js file replace const data isLoading error handleGetData useRequest with const useRequest BASE API suffix gt This just shows the function accepting the BASE API and suffix In your useRequest js replace const getData await axios get with const getData await axios get BASE API suffix Implement this for Axios to correctly get the BASE API and suffix endpoint Our final useRequest js file looks like this useRequest jsimport useState from react import axios from axios const useRequest BASE API suffix gt const data setData useState null const isLoading setIsLoading useState null const error setError useState null const handleGetData async gt setIsLoading true try const getData await axios get BASE API suffix if getData status setData getData data setIsLoading false else setError There was an error catch error setError error throw console error error return data isLoading error handleGetData export default useRequest A good practice is to keep your BASE API endpoint on your env file and your suffix on the file you want to use it on For example let s say we want to create a page for comments all we need to do is to create const suffix comments and use it like this DisplayComment jsconst BASE API const suffix comments const data isLoading error handleGetData useRequest BASE API suffix ConclusionIn this tutorial we created a react hook for handling custom interactions with an API we did this because we wanted to abstract the functionalities into a separate file This helps us to modularize our code and ensure that we don t repeat the same code in multiple files If you found this article helpful please like or leave a comment share it with your friends network who might need this and connect with me on Linkedin Twitter and hashnode 2023-06-27 08:14:11
海外TECH CodeProject Latest Articles CAPTCHA - How to Prevent Robot or Digital Entry on a Form which Could Lead to Causing Damages to Data https://www.codeproject.com/Tips/5362044/CAPTCHA-How-to-Prevent-Robot-or-Digital-Entry-on-a integration 2023-06-27 08:39:00
海外科学 NYT > Science Anthony Fauci to Teach at Georgetown University https://www.nytimes.com/2023/06/27/health/anthony-fauci-georgetown.html covid 2023-06-27 08:17:21
海外科学 NYT > Science Remnants of Cindy Could Redevelop, Meteorologists Say https://www.nytimes.com/article/tropical-storm-cindy-hurricane.html Remnants of Cindy Could Redevelop Meteorologists SayAn area of low pressure associated with remnants of the tropical storm was well out to sea on Tuesday and was producing disorganized showers and thunderstorms 2023-06-27 08:17:58
海外ニュース Japan Times latest articles Self-Defense Forces testing use of Musk’s Starlink satellite internet service https://www.japantimes.co.jp/news/2023/06/27/national/japan-sdf-starlink/ Self Defense Forces testing use of Musk s Starlink satellite internet serviceJapan already uses satellites in geostationary orbit but Starlink adds a constellation of low Earth orbit options to the mix 2023-06-27 17:40:41
海外ニュース Japan Times latest articles Deep in the countryside, a glimpse of Airbnb’s Japan strategy https://www.japantimes.co.jp/news/2023/06/27/business/corporate-business/airbnb-japan-strategy-growth/ Deep in the countryside a glimpse of Airbnb s Japan strategyThe short term lodging service is seeking to build links with communities outside of well beaten tourist pathways and entice travelers to rural areas 2023-06-27 17:29:17
海外ニュース Japan Times latest articles LDP and Komeito try to patch up differences with election deal https://www.japantimes.co.jp/news/2023/06/27/national/politics-diplomacy/ldp-komeito-election-deal/ general 2023-06-27 17:16:24
ニュース BBC News - Home Supermarket bosses to be grilled over high food prices https://www.bbc.co.uk/news/business-66019190?at_medium=RSS&at_campaign=KARANGA inflation 2023-06-27 08:46:01
ニュース BBC News - Home Trump heard on tape discussing 'highly confidential, secret' documents https://www.bbc.co.uk/news/world-us-canada-66027036?at_medium=RSS&at_campaign=KARANGA documentsit 2023-06-27 08:40:17
ニュース BBC News - Home Dragons' Den: Gary Neville to join BBC show as guest Dragon for 2024 series https://www.bbc.co.uk/sport/football/66028343?at_medium=RSS&at_campaign=KARANGA Dragons x Den Gary Neville to join BBC show as guest Dragon for seriesFormer Manchester United and England defender Gary Neville is to join Dragons Den as a guest Dragon for the series 2023-06-27 08:18:51
ビジネス ダイヤモンド・オンライン - 新着記事 「離婚しようと思うねん」明石家さんまに相談したら…“たった5文字”の返答にグッときた - ニュースな本 https://diamond.jp/articles/-/325190 「離婚しようと思うねん」明石家さんまに相談したら…“たった文字の返答にグッときたニュースな本吉本興業の「顔」だった大﨑洋さんが、日の株主総会をもって退社する。 2023-06-27 17:30:00
ビジネス ダイヤモンド・オンライン - 新着記事 会社が儲かっても「あなたの給料が増えない」理由、利益はどこへ消える? - ニュースな本 https://diamond.jp/articles/-/324978 会社が儲かっても「あなたの給料が増えない」理由、利益はどこへ消えるニュースな本多くの会社で賞与ボーナスが支払われる時期。 2023-06-27 17:15:00
GCP Google Cloud Platform Japan 公式ブログ Google Cloud 上で実行される Sembly AI の音声 AI プラットフォームにより職場の生産性が向上 https://cloud.google.com/blog/ja/topics/startups/sembly-voice-ai-running-on-google-cloud-boosts-productivity/ 当社は歴史の浅いスタートアップでしたが、GoogleCloudのおかげでテクノロジーを簡単にクラウドにデプロイし、管理できました。 2023-06-27 09:50:00
GCP Google Cloud Platform Japan 公式ブログ BigLake を使って Apache Iceberg レイクハウスを変革する https://cloud.google.com/blog/ja/products/data-analytics/biglake-support-for-building-apache-iceberg-lakehouses-is-now-ga/ CloudStorageまたはAmazonSに配置されたBigLakeIcebergテーブルは、AnalyticsHubで共有したり、BigQueryから、あるいはBigQueryStorageReadAPI経由でOSSエンジンから使用することができ、共有方法のオープンスタンダードとして、複数のクエリエンジンの使用を可能にしています。 2023-06-27 09:40:00
GCP Google Cloud Platform Japan 公式ブログ BigQuery と Vertex AI を使用した RNA シーケンスとタンパク質構造予測 https://cloud.google.com/blog/ja/topics/healthcare-life-sciences/rna-seq-and-protein-structure-prediction-on-google-cloud/ このブログでは、BigQueryとVertexAIをスケーラブルに利用してゲノムデータを処理するRNAシーケンスとタンパク質構造予測のエンドツーエンドのパイプラインを開発しました。 2023-06-27 09:30:00
GCP Google Cloud Platform Japan 公式ブログ Google Cloud iLB + Cloud DNS によるマルチリージョンの内部ロード バランシングの設計 https://cloud.google.com/blog/ja/products/networking/load-balancing-inside-public-cloud-options-and-optimizations/ 内部ロードバランサのグローバルアクセス機能により、クライアントはどのリージョンからでも特定のリージョンにデプロイされたサービスにロードバランサを介してトラフィックを送信できます。 2023-06-27 09:20:00
GCP Google Cloud Platform Japan 公式ブログ BigQuery Omni によるクロスクラウド地理空間解析のメリット https://cloud.google.com/blog/ja/products/data-analytics/bigquery-omni-for-cross-cloud-geospatial-analytics/ 受注Parquetファイル位置情報と郵便番号のファイルステップBigQueryOmniを使ってAWSに保存されているデータとBigQueryとの接続を確立し、Sデータセットに外部からアクセスできるようにします。 2023-06-27 09:10:00
IT 週刊アスキー 地図がデザインされた雑貨を手作り体験できる「Map Design GALLERY&LAB」ゼンリンがリニューアルオープン https://weekly.ascii.jp/elem/000/004/142/4142763/ mapdesigngalleryamplab 2023-06-27 17:50:00
IT 週刊アスキー ゾンビRPG『ゾンビ・オブ・ザ・ドット』がPS5/PS4/Switch/XSX|S/Xbox One/Steamで配信開始! https://weekly.ascii.jp/elem/000/004/142/4142817/ ゾンビRPG『ゾンビ・オブ・ザ・ドット』がPSPSSwitchXSXSXboxOneSteamで配信開始ケムコは、RPG『ゾンビ・オブ・ザ・ドット』をPlayStationPlayStationNintendoSwitchXboxSeriesXSXboxOnePCSteam向けに年月日より配信開始した。 2023-06-27 17:50:00
IT 週刊アスキー IIJ、1枚のSIMで複数のキャリアに接続可能な「マルチプロファイルSIM」提供開始 https://weekly.ascii.jp/elem/000/004/142/4142774/ 提供開始 2023-06-27 17:45:00
IT 週刊アスキー “レモン”がテーマのSummer限定メニュー登場 「カービィカフェ Summer 2023」7月6日~9月18日期間限定開催 https://weekly.ascii.jp/elem/000/004/142/4142753/ summer 2023-06-27 17:30:00
IT 週刊アスキー 最大75%オフ!コーエーテクモゲームスが「Steam Summer Sale」を開催 https://weekly.ascii.jp/elem/000/004/142/4142788/ steam 2023-06-27 17:20:00
IT 週刊アスキー 叙々苑でひとり焼肉。3000円でエグゼクティブな気分に https://weekly.ascii.jp/elem/000/004/142/4142702/ 絶対 2023-06-27 17:10:00
マーケティング AdverTimes ユニクロUTがコンセプト刷新、グローバルOOHで「カルチャーとの共存」宣言 https://www.advertimes.com/20230627/article424652/ withut 2023-06-27 08:13:46
マーケティング AdverTimes メルカリ、健全な再利用の研究・浸透を図る「リコマース総合研究所」設立 https://www.advertimes.com/20230627/article424809/ 循環型社会 2023-06-27 08:07:15
GCP Cloud Blog JA Google Cloud 上で実行される Sembly AI の音声 AI プラットフォームにより職場の生産性が向上 https://cloud.google.com/blog/ja/topics/startups/sembly-voice-ai-running-on-google-cloud-boosts-productivity/ 当社は歴史の浅いスタートアップでしたが、GoogleCloudのおかげでテクノロジーを簡単にクラウドにデプロイし、管理できました。 2023-06-27 09:50:00
GCP Cloud Blog JA BigLake を使って Apache Iceberg レイクハウスを変革する https://cloud.google.com/blog/ja/products/data-analytics/biglake-support-for-building-apache-iceberg-lakehouses-is-now-ga/ CloudStorageまたはAmazonSに配置されたBigLakeIcebergテーブルは、AnalyticsHubで共有したり、BigQueryから、あるいはBigQueryStorageReadAPI経由でOSSエンジンから使用することができ、共有方法のオープンスタンダードとして、複数のクエリエンジンの使用を可能にしています。 2023-06-27 09:40:00
GCP Cloud Blog JA BigQuery と Vertex AI を使用した RNA シーケンスとタンパク質構造予測 https://cloud.google.com/blog/ja/topics/healthcare-life-sciences/rna-seq-and-protein-structure-prediction-on-google-cloud/ このブログでは、BigQueryとVertexAIをスケーラブルに利用してゲノムデータを処理するRNAシーケンスとタンパク質構造予測のエンドツーエンドのパイプラインを開発しました。 2023-06-27 09:30:00
GCP Cloud Blog JA Google Cloud iLB + Cloud DNS によるマルチリージョンの内部ロード バランシングの設計 https://cloud.google.com/blog/ja/products/networking/load-balancing-inside-public-cloud-options-and-optimizations/ 内部ロードバランサのグローバルアクセス機能により、クライアントはどのリージョンからでも特定のリージョンにデプロイされたサービスにロードバランサを介してトラフィックを送信できます。 2023-06-27 09:20:00
GCP Cloud Blog JA BigQuery Omni によるクロスクラウド地理空間解析のメリット https://cloud.google.com/blog/ja/products/data-analytics/bigquery-omni-for-cross-cloud-geospatial-analytics/ 受注Parquetファイル位置情報と郵便番号のファイルステップBigQueryOmniを使ってAWSに保存されているデータとBigQueryとの接続を確立し、Sデータセットに外部からアクセスできるようにします。 2023-06-27 09:10:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)