Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="rick-and-morty"></div>
              
            
!

CSS

              
                :root {
  --dark-cyan: #02b1c8;
  --cyan: #00e1ff;
  --green: #7ffa67;
  --white: #fcfcfc;
  --black: #111;
  --darkest-grey: #151515;
  --dark-grey: #222;
  --grey: #333;
}

* {
  box-sizing: border-box;
}

html {
  scroll-behavior: smooth;
}

body {
  font-family: "Source Sans Pro", sans-serif;
  font-weight: 400;
  color: var(--white);
  min-height: 100vh;
  padding: 1.25rem;
  text-align: center;
  text-shadow: 0.0625rem 0.0625rem 0.0625rem var(--black);
  background: linear-gradient(rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.8)),
    var(--black) url(https://source.unsplash.com/RF4p4rTM-2s/1280x720) no-repeat
      center fixed;
  background-size: cover;
}

:focus {
  outline: 0.1875rem solid var(--dark-cyan);
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  border: 0;
}

.header {
  &__heading {
    font-family: "Schoolbell", cursive;
    font-size: calc(3rem + 2.7vw);
    line-height: 1;
    color: var(--dark-cyan);
    margin: 1.25rem 0 1.5625rem;
    text-shadow: 0.02em 0.02em 0.02em var(--green),
      -0.02em -0.02em 0.02em var(--green), 0 0 0.2em var(--green);

    span {
      font-size: 0.5em;
      margin: 0 -0.5ch;
      vertical-align: middle;
    }
  }
}

.search {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.625rem;
  margin-bottom: 1.875rem;

  &__label {
    font-size: 1.5625rem;
  }

  &__input {
    font-family: inherit;
    font-size: 1.25rem;
    max-width: 100%;
    width: 17.5rem;
    height: 2.1875rem;
    border: none;
    border-radius: 1rem;
    text-align: center;
    color: var(--black);
    background-color: var(--white);
    box-shadow: 0 0 0 0.1875rem rgba(0, 0, 0, 0.3);

    &:focus {
      outline: none;
      box-shadow: 0 0 0 0.1875rem var(--dark-cyan);
    }
  }
}

.results {
  max-width: 47rem;
  margin: 0 auto 1.25rem;

  &__info {
    font-size: 1.125rem;
    margin-bottom: 1rem;
  }

  &__message {
    font-size: 1.875rem;
  }
}

.loader {
  width: 3.125rem;
  height: 3.125rem;
  border: 0.25rem solid var(--white);
  border-top-color: transparent;
  border-radius: 50%;
  margin: 0 auto;
  animation: spin 500ms linear infinite;
}

.character {
  border-bottom: 0.125rem solid var(--darkest-grey);

  &__name {
    font-size: 1.75rem;
    font-weight: 600;
    line-height: 1.2;
    text-align: left;
    padding: 1.25rem;
    background-color: var(--dark-grey);
    cursor: pointer;
  }

  &__content {
    display: flex;
    flex-direction: column;
    gap: 1.5636rem;
    line-height: 1.2;
    padding: 1.5636rem;
    background-color: var(--grey);
    border-top: 0.125rem solid var(--darkest-grey);
  }

  &__info {
    flex: 1;
  }

  &__item {
    &-summary {
      font-size: 1.5636rem;
      font-weight: 400;
      color: var(--cyan);
      text-align: center;
      margin-bottom: 0.625rem;
      cursor: pointer;
    }

    &-info {
      font-size: 1.375rem;
      margin-bottom: 0.625rem;
    }
  }

  &__image {
    max-width: 100%;
    margin: auto;
    border: 0.3125rem solid var(--white);
    border-radius: 1.25rem;

    &-container {
      flex: 1;
      display: block;
      order: -1;
    }
  }
}

.pagination {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 1.25rem;
  margin-bottom: 1rem;

  &__info {
    flex-basis: 100%;
    font-size: 1.125rem;
  }

  &__btn {
    display: inline-block;
    font: inherit;
    font-size: 1.375rem;
    font-weight: 600;
    background: none;
    border: none;
    min-width: 8.4375rem;
    color: inherit;
    padding: 0.625rem;
    cursor: pointer;
    background-color: var(--dark-grey);
    box-shadow: 0 0 0 0.1875rem var(--grey);
  }
}

@media (min-width: 600px) {
  .character {
    &__content {
      flex-direction: row;
    }

    &__image {
      &-container {
        display: flex;
        order: 0;
      }
    }
  }
}

@keyframes spin {
  to {
    transform: rotate(1turn);
  }
}

              
            
!

JS

              
                const { useState, useEffect, useRef, useMemo } = React
const { createRoot } = ReactDOM
const container = document.querySelector('#rick-and-morty')
const root = createRoot(container)

const RickAndMorty = () => {
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [searchTerm, setSearchTerm] = useState('')
  const [searching, setSearching] = useState(true)
  const [searched, setSearched] = useState(false)
  const [characters, setCharacters] = useState([])
  const [totalCharacters, setTotalCharacters] = useState(0)
  const [error, setError] = useState(false)

  const firstCharacter = useRef(null)

  const apiUrl = 'https://rickandmortyapi.com/api/character/'

  const handleSearchInput = useMemo(() =>
    debounce(value => {
      setPage(1)
      setSearchTerm(value)
      setSearching(true)
      setSearched(true)
    })
  )

  const handlePageChange = page => {
    setPage(prevPage => prevPage + page)
    setSearched(true)
  }

  useEffect(() => {
    const fetchController = new AbortController()
    
    fetch(`${apiUrl}?page=${page}&name=${searchTerm}`)
      .then(res => res.json())
      .then(data => {
        if (data.error) {
          // No results
          setTotalPages(1)
          setCharacters([])
        } else {
          // Results found
          setTotalPages(data.info.pages)
          setTotalCharacters(data.info.count)
          setCharacters([...data.results])
        }
        // Reset any previous error state
        setError(false)
      })
      .catch(() => {
        // Error fetching from API
        setError(true)
        setTotalPages(1)
        setCharacters([])
      })
      .finally(() => setSearching(false))
    
    return () => fetchController.abort()
  }, [searchTerm, page])

  useEffect(() => {
    if (searched && characters.length > 0) {
      // Focus first character in list
      firstCharacter.current.focus()
    }
  }, [characters])

  return (
    <>
      <Header />
      <main>
        <Search
          handleSearchInput={ e => handleSearchInput(e.target.value) }
        />
        <Results
          page={ page }
          totalPages={ totalPages }
          characters={ characters }
          firstCharacter={ firstCharacter }
          totalCharacters={ totalCharacters }
          searching={ searching }
          error={ error }
        />
        {
          !searching && totalPages > 1 && (
            <Pagination
              page={ page }
              totalPages={ totalPages }
              prevPage={ () => handlePageChange(-1) }
              nextPage={ () => handlePageChange(1) }
            />
          )
        }
      </main>
    </>
  )
}

const Header = () => {
  return (
    <header className='header'>
      <h1 className='header__heading'>
        Rick <span>And</span> Morty
      </h1>
    </header>
  )
}

const Search = ({ handleSearchInput }) => {
  return (
    <div className='search'>
      <label htmlFor='search' className='search__label'>
        Character Search:
      </label>
      <input
        type='text'
        id='search'
        className='search__input'
        placeholder='e.g. rick'
        spellCheck='false'
        onChange={ handleSearchInput }
      />
    </div>
  )
}

const Results = ({
  page,
  totalPages,
  characters,
  firstCharacter,
  totalCharacters,
  searching,
  error
}) => {
  return (
    <div className='results' aria-live='polite'>
      {
        searching ? (
          <Loader />
        ) : (
          <>
            {
              characters.length > 0 ? (
                <>
                  <p className='results__info'>
                    Showing { (page - 1) * characters.length + 1 }-{ page === totalPages ? totalCharacters : page * characters.length } of { totalCharacters } characters
                  </p>
                  {
                    characters.map((character, index) => (
                      <Character
                        character={ character }
                        key={ character.id }
                        index={ index }
                        firstCharacter={ firstCharacter }
                      />
                    ))
                  }
                </>
              ) : (
                error ? (
                  <p className='results__message'>Error Retrieving Characters</p>
                ) : (
                  <p className='results__message'>No Characters Found</p>
                )
              )
            }
          </>
        )
      }

    </div>
  )
}

const Loader = () => {
  return (
    <div className='loader'>
      <span className='sr-only'>Loading</span>
    </div>
  )
}

const Character = ({ character, firstCharacter, index }) => {
  return (
    <details className='character'>
      <summary
        className='character__name'
        ref={ index === 0 ? firstCharacter : null }
      >
        { character.name }
      </summary>
      <div className='character__content'>
        <div className='character__info'>
          <details className='character__item' open>
            <summary className='character__item-summary'>Name</summary>
            <p className='character__item-info'>{ character.name }</p>
          </details>
          <details className='character__item' open>
            <summary className='character__item-summary'>Species</summary>
            <p className='character__item-info'>{ character.species }</p>
          </details>
          <details className='character__item' open>
            <summary className='character__item-summary'>Gender</summary>
            <p className='character__item-info'>{ character.gender }</p>
          </details>
          <details className='character__item' open>
            <summary className='character__item-summary'>Location</summary>
            <p className='character__item-info'>{ character.location.name }</p>
          </details>
        </div>
        <div className='character__image-container'>
          <img
            className='character__image'
            src={ character.image }
            alt={ character.name }
          />
        </div>
      </div>
    </details>
  )
}

const Pagination = ({ page, totalPages, prevPage, nextPage }) => {
  return (
    <nav className='pagination' aria-label="page navigation">
      <p className='pagination__info'>
        Page { page } of { totalPages }
      </p>
      {
        page > 1 && (
          <button className='pagination__btn' onClick={ prevPage }>
            Prev Page
          </button>
        )
      }
      {
        page < totalPages && (
          <button className='pagination__btn' onClick={ nextPage }>
            Next Page
          </button>
        )
      }
    </nav>
  )
}

const debounce = (func, wait = 800) => {
  let timeout

  return function () {
    const context = this
    const args = arguments

    clearTimeout(timeout)

    timeout = setTimeout(() => {
      timeout = null
      func.apply(context, args)
    }, wait)
  }
}

root.render(<RickAndMorty />)

console.log('Wubba Lubba Dub-Dub! πŸ‘΄πŸ»πŸ‘¦πŸΎπŸ”¬πŸ”«πŸŒŒπŸš€πŸ›ΈπŸ‘Ύ');
              
            
!
999px

Console