Git Product home page Git Product logo

chalarangelo / 30-seconds-of-react Goto Github PK

View Code? Open in Web Editor NEW
5.0K 110.0 482.0 3.76 MB

Short React code snippets for all your development needs

Home Page: https://www.30secondsofcode.org/react/p/1

License: Creative Commons Attribution 4.0 International

JavaScript 100.00%
react reactjs snippets snippets-collection learning-resources learn-to-code programming education javascript snippets-library

30-seconds-of-react's Introduction

IMPORTANT NOTICE:

As of May, 2023, all 30-seconds content repositories have been merged into 30-seconds-of-code.

Please watch, star and follow relevant activity there.

Logo

30 seconds of code

Short React code snippets for all your development needs

  • Visit our website to view our snippet collection.
  • Use the Search page to find snippets that suit your needs. You can search by name, tag, language or using a snippet's description. Just start typing a term and see what comes up.
  • Browse the React Snippet collection to see all the snippets in this project or click individual tags at the top of the same page to narrow down your search to a specific tag.
  • Click on each snippet card to view the whole snippet, including code, explanation and examples.
  • You can use the button at the bottom of a snippet card to view the snippet in Codepen.
  • If you like the project, give it a star. It means a lot to the people maintaining it.

Want to contribute?

Credits

  • This repository is maintained by the 30 seconds of code organization on GitHub.
  • All snippets are licensed under the CC-BY-4.0 License, unless explicitly stated otherwise.
  • Logos, names and trademarks are not to be used without the explicit consent of the owners of the 30 seconds of code GitHub organization.
  • Our website is powered by Netlify, Next.js & GitHub.

30-seconds-of-react's People

Contributors

30secondsofcode avatar a13marquez avatar arjunmahishi avatar atomiks avatar bluedusk avatar chalarangelo avatar citguy avatar danibonilha avatar dasdachs avatar dependabot[bot] avatar dmtrjs avatar dusch4593 avatar fejes713 avatar gianpaj avatar giselamd avatar maltea avatar ositowang avatar phaniteja1 avatar prvnbist avatar raurir avatar rishichawda avatar sellalone avatar skatcat31 avatar stereobooster avatar theodorusyoga avatar timonvs avatar trinityyi avatar tshma avatar vinamelody avatar witoszekdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

30-seconds-of-react's Issues

[CHORE] Contributing Guidelines

We have a template for snippets, now we just need a contributing guideline and people can contribute before we get in the scripts.

We should also update our snippet template with a tests header to be extracted for testing purposes. This way we can generate the tests, and the README and the Site can skip them and we won't need another separate file this time. Just one file, split on specific headers and patterns, export them to the right scripts, and off to the races.

This would also greatly simplify our contributing guidelines since now we don't have to worry about explaining the tag file, snippet file, or tests file. Now everything is a single markdown.

Use an extra param with `useInterval` hook to stop JS Interval based on condition

Background

I was doing some tweaks with the setInterval function in React. Then, I found the useInterval hook here. The problem I've faced with this hook is I can't stop the interval without unmounting the component. I wanted to stop the interval after a certain time. But I found no options here. Or did I miss something?

Screenshot 2021-05-19 at 10 09 13 AM

Solution

We can add an extra param with useInterval hook that will stop the interval when it's true. Like the following example:

useInterval(
    () => {
      setProgress(progress + 1);
      setTime(time + intervalDelay);
    },
    intervalDelay,
    progress >= initialyCompleted // This is the third param for clearing Interval manually
);

If this issue is valid, then could you please assign this issue to me? I have a working solution and I want to contribute here. Thanks so much.

[CHORE] Continuous Integration

As usual, we have to set up Travis CI, let the bot do its thing and make daily builds and on-demand builds. of the repo.

Start new Laravel project issue

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for league/flysystem 1.0.49 -> satisfiable by league/flysystem[1.0.49].
- league/flysystem 1.0.49 requires ext-fileinfo * -> the requested PHP extension fileinfo is missing from your system.
Problem 2
- league/flysystem 1.0.49 requires ext-fileinfo * -> the requested PHP extension fileinfo is missing from your system.
- laravel/framework v5.7.22 requires league/flysystem ^1.0.8 -> satisfiable by league/flysystem[1.0.49].
- Installation request for laravel/framework v5.7.22 -> satisfiable by laravel/framework[v5.7.22].

To enable extensions, verify that they are enabled in your .ini files:
- C:\PHP7\php.ini
You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

usePersistedState — Should first useEffect have dependencies?

In usePersistedState.md, the following function is shown:

  React.useEffect(() => {
    try {
      const storedValue = localStorage.getItem(name);
      if (storedValue !== null) setValue(storedValue);
      else localStorage.setItem(name, defaultValue);
    } catch {
      setValue(defaultValue);
    }
  }, []);

I was wondering if it should have the defaultValue and name as dependencies to allow the hook to be re-initialized even if it was already mounted?

  React.useEffect(() => {
    try {
      const storedValue = localStorage.getItem(name);
      if (storedValue !== null) setValue(storedValue);
      else localStorage.setItem(name, defaultValue);
    } catch {
      setValue(defaultValue);
    }
  }, [defaultValue, name]);

If not, would it make sense to expand the example/documentation to include a note about eslint react-hook dependency warnings that may trigger, to avoid confusion about whether there is a bug in the implementation or if eslint is unaware of the context as to why the choice was made.

Thanks for your time and consideration.

useAsync hook


title: useAsync
tags: react,intermediate,hook

The useAsync hook is used to bind asynchronous call and handle different states like loading, error, and value. According to the state of an asynchronous call, we can render different states like loading, error and value state.

Explanation:
In useAsync hook we need to pass the handler function and that will be called after calling the run method. Once run get's called we're changing loading, error and value field according to asynchronous call response.

const useAsync = (fn, options = {}) => {
  const autoRun = options.autoRun || false

  const [state, setState] = React.useState({
    error: null,
    loading: false,
    value: null,
  })

  const handleStateChange = args => {
    setState({ ...state, ...args })
  }

  const run = async (args = null) => {
    try {
      handleStateChange({ loading: true, error: null })
      const value = await fn(args)
      handleStateChange({ loading: false, value: value || null, error: null })
    } catch (error) {
      handleStateChange({ loading: false, value: null, error })
    }
  }

  React.useEffect(() => {
    if (autoRun) {
      run()
    }
  }, [autoRun])

  return {
    state,
    setState,
    run,
  }
}

Usages

const App = () => {
  const handleSubmit = () => {
    const url = "https://jsonplaceholder.typicode.com/todos"
    return fetch(url).then(response => response.json())
  }

  const submission = useAsync(handleSubmit, { autoRun: false })

  return (
    <div>
      {submission.value && <div>{submission.value}</div>}
      <button
        onClick={() => submission.run({ foo: "bar" })}
        disabled={submission.loading}
      >
        click me
      </button>
    </div>
  )
}

adding test suite for components and hooks

Description

Hi,

This is one of the extremely helpful projects I've ever seen. In this issue, I want to discuss "Do you've any plan to add test suite?". Sometimes I feel like we're using snippets on production so we need to have a test suite which will give us solid confidence.

Anyway, Thanks for maintaining this project.

[CHORE] Builder Script

As soon as we decide on a format for snippets and get a few going, we need to make a builder script with all the necessary components.

[CHORE] Linter

We definitely need a linter/formatter for snippets, like eslint + prettier only that it has to work with JSX, too. Can someone please suggest some options and/or help implement them?

[FEATURE] 30 seconds of code - React snippets

From @Chalarangelo on September 10, 2018 20:37

After some internal discussion and the idea floating around for a bit, I think we should go ahead and brainstorm a bit about adding React snippets in the repository, as a separate page, folder etc.

The idea is to provide a basic cheatsheet for React, much like the base repository, except this will be a sub-project (as it is part of the JS ecosystem and we are probably not going to have snippets in the hundreds in this category). I've started compiling a list of popular StackOverflow questions and answers that might prove useful. Add your suggestions below and let's get a decently-sized list ready for October, when Hacktoberfest starts and we can expect a decent flow of PRs.

My completely incomplete list of ideas

  • Collapse #11
  • Rating #12
  • Tooltip #22
  • Modal dialog #17
  • Array.map() to create a row in a table (or similar) / SO question #9 and #26
  • Array.map() to render a list #8
  • Toggle #20
  • Autolink (convert link from text to actual <a> element with link) #27
  • Tabs #38
  • Carousel #23
  • Drop area file uploader #41
  • Tree view #43
  • Timer / Clock / Countdown #33
  • Slider 8dfdcfd
  • Accordion c0177c0
  • Lazy loader / infinite scroller
  • Overlay / dock
  • Lightbox / image preview
  • Notification / alert
  • Hamburger menu / navigation bar
  • Loader / progress
  • Custom scrollbar
  • Audio / video player
  • Image gallery
  • Calendar
  • Date/time picker
  • Autofocusing input (with additional attributes)
  • Credit card input
  • Color picker
  • Tag input field
  • Rich text editor (support simple things like Bold, Italics, Underline etc.)
  • Image cropper
  • Customizable grid
  • Resizer
  • Combobox

My completely incomplete list of ideas (old)

Copied from original issue: Chalarangelo/30-seconds-of-code#739

[CHORE] Snippet Template

We don't have a template for snippets in this repository yet. We should figure this out and create a template as soon as possible.

Update template

We use arrow functions instead of function declarations after the last curation effort. Let's make sure the template reflects that.

LimitedTextarea: A little additional detail on useEffect

Thanks for these snippets! 🎉

The LimitedTextarea snippet sent me on a good learning journey about useEffect, these tweaks would have got me there a little faster I think:

  • A few more words about the result of the useEffect dependency array.
  • Add limit to the useEffect dependencies.
  • Value -> initialValue to express the behaviour a bit more specifically.

Got a commit here with proposed changes.

I'll turn it into a PR if there's positive feedback.

Hoping to make some more substantial contributions soon!

P.S here's a sandbox I setup to test out the changes: https://codesandbox.io/s/yq177rjz9x

Restructure descriptions to dot points

They're fairly hard to read atm since they're quite long. The paragraph structure doesn't translate as well to this repo since they can get much more verbose.

Wrong link to Input example in the table of content

I noticed that there's wrong link to Input example in the table of content. It doesn't match:

https://github.com/30-seconds/30-seconds-of-react#input - actual(wrong)
https://github.com/30-seconds/30-seconds-of-react#input-2 - in the content

MailTo Encoding

  1. Using special characters in mailto: strings causes Outlook (and possibly other email clients) to stop parsing the string.

Example:

ReactDOM.render(
  <Mailto email="[email protected]" subject="Hello & Welcome" body="Hello & Welcome world!">
    Mail me!
  </Mailto>,
  document.getElementById('root')
);

// result: mailto will stop being parsed at the first ampersand, ignoring the body

Suggestion: Encode subject and body strings:

function Mailto({ email, subject, body, ...props }) {
  return (
    <a href={`mailto:${email}?subject=${encodeURIComponent(subject) || ''}&body=${encodeURIComponent(body) || ''}`}>{props.children}</a>
  );
}

Convert all snippets to use hooks

Hooks have been officially merged and will be released soon, they're the recommended way to create components moving forward.

When you’re ready, we’d encourage you to start trying Hooks in new components you write.

I think we should discourage using classes and use function components + hooks for everything. This also negates the "public class fields" debate that was happening here last year lol.

cancel an HTTP fetch() request at useFetch hooks

when we are doing http request and not yet completed the request, but we unmount the hooks or the component, then we will get error, because the http request still running and when completed then we do change state setResponse(json); or setError(error);.

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount
method.

Solution
we should cancel the subscriptions of fetching, when the component will unmount.

reference to fix:
https://stackoverflow.com/questions/31061838/how-do-i-cancel-an-http-fetch-request
https://stackoverflow.com/questions/53949393/cant-perform-a-react-state-update-on-an-unmounted-component

Add imgs folder under snippets

I do think there should be a folder named imgs or pics under snippets for storing some pics that illustrated the code if needed.

Revamp tagging for snippets

Due to the way we display snippets, it would make much more sense to only differentiate between two tag types - Components and Hooks. All existing snippets should be retagged to fall under one of the two categories.

clerical error

Bug description

should be 'React.useState()'

Steps to reproduce

Expected behavior

Screenshots

image

Environment

[CHORE] Website

Ideally, we would publish under react.30secondsofcode.org and include this repo as a submodule in the 30code repo.

We need a script, static parts and a decent design for this.

[CountDown]something wrong with this component

hi, l think some code in CountDown component may be not right,
image

l think this is not the rihgt way in using hooks, it will always clearinterval after every render, just like this
image
l think this need to be fixed, l can do it if you need :)

Update codebase to use const instead of function

Currently, all components use function instead of const. We should update the code to use that. Assigning to @Trinityyi as a starter maintenance task.

Additionally:

  • Convert components that have no side-effects to use implicit returns.
  • Separate props into individual lines when lines get very long.
  • Check for missing keys and open issues where appropriate.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.