Snippets Collections
export function TailwindIndicator() {
  if (process.env.NODE_ENV === "production") return null

  return (
    <div className="fixed bottom-1 left-1 z-50 flex h-6 w-6 items-center justify-center rounded-full bg-gray-800 p-3 font-mono text-xs text-white">
      <div className="block sm:hidden">xs</div>
      <div className="hidden sm:block md:hidden">sm</div>
      <div className="hidden md:block lg:hidden">md</div>
      <div className="hidden lg:block xl:hidden">lg</div>
      <div className="hidden xl:block 2xl:hidden">xl</div>
      <div className="hidden 2xl:block">2xl</div>
    </div>
  )
}
module.exports = {

  safelist: [

    {

      pattern: /text-(base|xl|2xl|4xl)/,

    },

  ],

};
import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
  const [car, setCar] = useState({
    brand: "Ford",
    model: "Mustang",
    year: "1964",
    color: "red"
  });

  const updateColor = () => {
    setCar(previousState => {
      return { ...previousState, color: "blue" }
    });
  }

  return (
    <>
      <h1>My {car.brand}</h1>
      <p>
        It is a {car.color} {car.model} from {car.year}.
      </p>
      <button
        type="button"
        onClick={updateColor}
      >Blue</button>
    </>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
import {useState} from 'react';

export default function App() {
  const [isSubscribed, setIsSubscribed] = useState(false);

  const handleChange = event => {
    setIsSubscribed(event.target.checked);

    // 👇️ this is the checkbox itself
    console.log(event.target);

    // 👇️ this is the checked value of the field
    console.log(event.target.checked);
  };

  return (
    <div>
      <label htmlFor="subscribe">Subscribe</label>
      <input
        type="checkbox"
        id="subscribe"
        name="subscribe"
        onChange={handleChange}
        checked={isSubscribed}
      />
    </div>
  );
}
import {useRef} from 'react';

export default function App() {
  const ref = useRef(null);

  const handleClick = () => {
    // 👇️ get checkbox value with ref
    console.log(ref.current.checked);
  };

  return (
    <div>
      <input
       ref={ref}
       type="checkbox"
       id="subscribe"
       name="subscribe"
       defaultChecked={true}
      />

      <button onClick={handleClick}>Click</button>
    </div>
  );
}
import { useState, useMemo } from "react";
import ReactDOM from "react-dom/client";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  const calculation = useMemo(() => expensiveCalculation(count), [count]);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
      <div>
        <h2>My Todos</h2>
        {todos.map((todo, index) => {
          return <p key={index}>{todo}</p>;
        })}
        <button onClick={addTodo}>Add Todo</button>
      </div>
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
        <h2>Expensive Calculation</h2>
        {calculation}
      </div>
    </div>
  );
};

const expensiveCalculation = (num) => {
  console.log("Calculating...");
  for (let i = 0; i < 1000000000; i++) {
    num += 1;
  }
  return num;
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";

const UserContext = createContext();

function Component1() {
  const [user, setUser] = useState("Jesse Hall");

  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 />
    </UserContext.Provider>
  );
}

function Component2() {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 />
    </>
  );
}

function Component3() {
  return (
    <>
      <h1>Component 3</h1>
      <Component4 />
    </>
  );
}

function Component4() {
  return (
    <>
      <h1>Component 4</h1>
      <Component5 />
    </>
  );
}

function Component5() {
  const user = useContext(UserContext);

  return (
    <>
      <h1>Component 5</h1>
      <h2>{`Hello ${user} again!`}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);
import { useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const inputElement = useRef();

  const focusInput = () => {
    inputElement.current.focus();
  };

  return (
    <>
      <input type="text" ref={inputElement} />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const previousInputValue = useRef("");

  useEffect(() => {
    previousInputValue.current = inputValue;
  }, [inputValue]);

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h2>Current Value: {inputValue}</h2>
      <h2>Previous Value: {previousInputValue.current}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
import { useReducer } from "react";
import ReactDOM from "react-dom/client";

const initialTodos = [
  {
    id: 1,
    title: "Todo 1",
    complete: false,
  },
  {
    id: 2,
    title: "Todo 2",
    complete: false,
  },
];

const reducer = (state, action) => {
  switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};

function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);

  const handleComplete = (todo) => {
    dispatch({ type: "COMPLETE", id: todo.id });
  };

  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => handleComplete(todo)}
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);
import React from 'react';
import ReactDOM from 'react-dom/client';

function Hello(props) {
  return <h1>Hello World!</h1>;
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Hello />);
function Car(props) {
  return <h2>I am a { props.brand }!</h2>;
}

function Garage() {
  return (
    <>
      <h1>Who lives in my garage?</h1>
      <Car brand="Ford" />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home />} />
          <Route path="blogs" element={<Blogs />} />
          <Route path="contact" element={<Contact />} />
          <Route path="*" element={<NoPage />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
function Person({data}) {
  return (
    <div>
      <h2>{data.name}</h2>
      <h2>{data.age}</h2>
      <h2>{data.country}</h2>
    </div>
  );
}

export default function App() {
  const obj = {name: 'Alice', age: 29, country: 'Austria'};

  return (
    <div>
      <Person data={obj} />
    </div>
  );
}
function WindowSizeList({ url }) {
  const [windowWidth, setWindowWidth] = useState(window.innerWidth)
  const [items, setItems] = useState([])

  const updateWindowWidth = () => {
    setWindowWidth(window.innerWidth)
  }

  // TODO: Update list when url changes or on mount
  // TODO: Setup resize event listener on mount
  // TODO: Cleanup resize event listener on un-mount

  return (
    <>
      <div>Window Width: {windowWidth}</div>
      {items.map(item => {
        return <div key={item}>{item}</div>
      })}
    </>
  )
}
var AccountMainMenu = React.createClass({
  getInitialState: function() {
    return { focused: 0 };
  },

  clicked: function(index) {
    this.setState({ focused: index });
  },

  render: function() {
    var self = this;
    var accountMenuData = [
      {
        name: "My Account",
        icon: "icon-account"
      },
      {
        name: "Messages",
        icon: "icon-message"
      },
      {
        name: "Settings",
        icon: "icon-settings"
      }
    /*{
        name:"Help &amp; Support &nbsp; <span class='font-awesome icon-support'></span>(888) 664.6261",
        listClass:"no-mobile last help-support last"
      }*/
    ];

    return (
      <div className="acc-header-wrapper clearfix">
        <ul className="acc-btns-container">
          {accountMenuData.map(function(data, index) {
            var activeClass = "";

            if (self.state.focused == index) {
              activeClass = "active";
            }

            return (
              <li
                key={index}
                className={activeClass}
                onClick={self.clicked.bind(self, index)}
              >
                <a href="#" className={data.icon}>
                  {data.name}
                </a>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
});

ReactDOM.render(<AccountMainMenu />, document.getElementById("app-container"));
<span>Email us:&nbsp;<a href="mailto:yourcompany@gmail.com">yourcompany@gmail.com</a></span>
function Search({ onSearch }) {
  const [value, setValue] = React.useState('')

  // This is the solution
  const debouncedSearch = React.useMemo(
    () =>
      debounce(val => {
        onSearch(val)
      }, 750),
    [onSearch]
  )

  const handleChange = React.useCallback(
    e => {
      setValue(e.target.value)
      debouncedSearch(e.target.value)
    },
    [debouncedSearch]
  )

  return <input type="text" value={value} onChange={handleChange} />
}
import React from "react";

const Image = ({ name }) => {
  try {
    // Import image on demand
    const image = require(`assets/${name}`);

    // If the image doesn't exist. return null
    if (!image) return null;
    return <img src={image.default} />;
  } catch (error) {
    console.log(`Image with name "${name}" does not exist`);
    return null;
  }
};

export default Image;
import React from "react";
import ProgressiveImage from "react-progressive-image";

import image from "./image.jpg";
import placeholderImage from "./placeholderImage.jpg";

const App = () => {
  return (
    <ProgressiveImage src={image} placeholder="data:image/png;base64***">
      {(src) => <img src={src} alt="an image" />}
    </ProgressiveImage>
  );
};

export default App;
import React from "react";
import ProgressiveImage from "react-progressive-image";

import image from "./image.jpg";
import placeholderImage from "./placeholderImage.jpg";

const App = () => {
  /**
   * `placeholder` will be displayed 
   * while the original `src` image is being loaded
   */
  return (
    <ProgressiveImage src={image} placeholder={placeholderImage}>
      {(src) => <img src={src} alt="an image" />}
    </ProgressiveImage>
  );
};

export default App;
import React from "react";
import LazyLoad from "react-lazyload";

import image from "./image.jpg";

const App = () => {
  /**
   * Lazy loading images is supported out of box, no extra config is needed
   * `height` is set for better experience
   */
  return (
    <LazyLoad height={200}>
      <img src={image} />
    </LazyLoad>
  );
};

export default App;
import React from 'react';

function App() {

  function handleChange(event) {
    console.log(event.target.value);
  }
  
  return (
    <input name="firstName" onChange={handleChange} />
  );
}

export default App;
  ... 
  
  return (
    <input name="firstName" onChange={handleChange} />
  );
  
  ...
<section style={{backgroundColor: color}}></section>
const React = require('react')
class Upload extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      file: null
    }
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event) {
    this.setState({
      file: URL.createObjectURL(event.target.files[0])
    })
  }
  render() {
    return (
      <div>
        <input type="file" onChange={this.handleChange}/>
        <img src={this.state.file}/>
      </div>
    );
  }
}
module.exports = Upload
import React from 'react';

function App() {
  
  function refreshPage() {
    window.location.reload(false);
  }
  
  return (
    <div>
      <button onClick={refreshPage}>Click to reload!</button>
    </div>
  );
}

export default App;
// will need a HTML page with "root"

import React from "react";
import ReactDOM from "react-dom";

const date = new Date();
const currentTime = date.getHours();
const currentMins = date.getMinutes();

let greeting;

const customSyle = {
  color: ""
};

if (currentTime < 12) {
  greeting = "good morning";
  customSyle.color = "red";
} else if (currentTime < 18) {
  greeting = "good evening";
  customSyle.color = "blue";
} else {
  greeting = "good night";
  customSyle.color = "puprle";
}

ReactDOM.render(
  <h1 className="heading" style={customSyle}>
    {currentTime + ":" + currentMins + " " + greeting}
  </h1>,

  document.getElementById("root")
);
MyCo.propTypes = {
  list: PropTypes.array,
  ages: PropTypes.arrayOf(PropTypes.number),
  user: PropTypes.object,
  user: PropTypes.objectOf(PropTypes.number),
  message: PropTypes.instanceOf(Message)
}
class TodoList extends Component {
  render () {
    const { items } = this.props

    return <ul>
      {items.map(item =>
        <TodoItem item={item} key={item.key} />)}
    </ul>
  }
}

 

 
function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

 

 

 

 

 
MyCo.propTypes = {
  list: PropTypes.array,
  ages: PropTypes.arrayOf(PropTypes.number),
  user: PropTypes.object,
  user: PropTypes.objectOf(PropTypes.number),
  message: PropTypes.instanceOf(Message)
}
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
React.createClass({ ... })
React.isValidElement(c)
class Hello extends Component {
    state = { visible: true }
  }
}
class Hello extends Component {
  constructor (props) {
    super(props)
    this.state = { visible: true }
  }
}

 
star

Sat Mar 16 2024 23:38:29 GMT+0000 (Coordinated Universal Time) https://github.com/shadcn-ui/taxonomy/blob/main/app/(auth)/login/page.tsx

#react #react.js #javascript #jsx #tailwind #css
star

Tue Apr 04 2023 08:21:32 GMT+0000 (Coordinated Universal Time) https://www.codeconcisely.com/posts/tailwind-css-dynamic-class/

#jsx
star

Sun Mar 12 2023 06:35:07 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_usestate.asp

#jsx
star

Fri Oct 28 2022 15:00:10 GMT+0000 (Coordinated Universal Time) https://bobbyhadz.com/blog/react-ref-checkbox

#jsx
star

Fri Oct 28 2022 15:00:06 GMT+0000 (Coordinated Universal Time) https://bobbyhadz.com/blog/react-ref-checkbox

#jsx
star

Thu Oct 27 2022 02:35:06 GMT+0000 (Coordinated Universal Time)

#inlinestyle #inlinecss #jsx #reactjs
star

Wed Sep 21 2022 05:59:42 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_usememo.asp

#jsx
star

Wed Sep 21 2022 03:39:29 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_usecontext.asp

#jsx
star

Wed Sep 21 2022 03:39:19 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_useref.asp

#jsx
star

Wed Sep 21 2022 03:39:12 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_useref.asp

#jsx
star

Wed Sep 21 2022 03:38:28 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_usereducer.asp

#jsx
star

Wed Sep 21 2022 02:35:17 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/default.asp

#jsx
star

Wed Aug 17 2022 19:31:15 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_props.asp

#jsx
star

Mon Jul 25 2022 17:27:13 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/react/react_router.asp

#jsx
star

Thu Jul 21 2022 06:18:14 GMT+0000 (Coordinated Universal Time) https://bobbyhadz.com/blog/react-pass-object-as-props

#jsx ##react ##object
star

Tue Jun 28 2022 13:11:17 GMT+0000 (Coordinated Universal Time) https://blog.webdevsimplified.com/2020-04/use-effect/

#jsx
star

Fri Jun 03 2022 08:52:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/34521797/how-to-add-multiple-classes-to-a-reactjs-component

#jsx
star

Mon May 23 2022 22:28:39 GMT+0000 (Coordinated Universal Time) https://techstacker.com/how-to-add-white-space-between-elements-react-jsx/

#jsx
star

Fri May 13 2022 15:39:57 GMT+0000 (Coordinated Universal Time) https://kyleshevlin.com/debounce-and-throttle-callbacks-with-react-hooks

#jsx
star

Thu May 05 2022 07:13:36 GMT+0000 (Coordinated Universal Time) https://www.upbeatcode.com/react/where-to-store-images-in-react-app/

#jsx
star

Thu May 05 2022 07:11:56 GMT+0000 (Coordinated Universal Time) https://www.upbeatcode.com/react/where-to-store-images-in-react-app/

#jsx
star

Thu May 05 2022 07:11:30 GMT+0000 (Coordinated Universal Time) https://www.upbeatcode.com/react/where-to-store-images-in-react-app/

#jsx
star

Thu May 05 2022 07:10:11 GMT+0000 (Coordinated Universal Time) https://www.upbeatcode.com/react/where-to-store-images-in-react-app/

#jsx
star

Tue Jan 04 2022 20:57:30 GMT+0000 (Coordinated Universal Time) https://upmostly.com/tutorials/react-onchange-events-with-examples

#jsx
star

Tue Jan 04 2022 20:51:57 GMT+0000 (Coordinated Universal Time) https://upmostly.com/tutorials/react-onchange-events-with-examples

#jsx
star

Tue Sep 28 2021 08:54:15 GMT+0000 (Coordinated Universal Time)

#jsx #react.js #inlinestyling
star

Sun May 23 2021 13:58:44 GMT+0000 (Coordinated Universal Time) https://medium.com/@650egor/react-30-day-challenge-day-2-image-upload-preview-2d534f8eaaa

#jsx
star

Fri May 21 2021 07:12:43 GMT+0000 (Coordinated Universal Time) https://upmostly.com/tutorials/how-to-refresh-a-page-or-component-in-react

#jsx
star

Wed Jun 03 2020 16:25:28 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Wed Jun 03 2020 16:25:20 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Wed Jun 03 2020 16:25:04 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Wed Jun 03 2020 16:25:01 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Sat May 23 2020 21:35:38 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Sat May 23 2020 21:34:17 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Sat May 23 2020 21:34:09 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Sat May 23 2020 21:32:47 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx
star

Sat May 23 2020 21:32:40 GMT+0000 (Coordinated Universal Time) https://devhints.io/react

#jsx

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension