Get started with JN Snippets

JN Snippets is a powerful, feature-packed frontend toolkit. Build anything—from prototype to production—in minutes.

  • # Install React using CLI

    npm install -g create-react-app
    npx create-react-app my-react-app
    cd my-react-app
    npm start

    Main File Where need to work
    In SRC Folder there is index.js this is our main file (so don’t touch this file) There is another app.js file so work on to that file.

    In react everything is Component to do any work first need to create component there are two type of components
    A. Class Component
    B. Functional Component

    For Beginners I would suggest use functional component they are easy to use and easy to learn (in short very easy)

    Firstly in every component don’t forget to import react.
    Then create a function and use any name for it then there is a return value of function. Your most of the code goes inside the return.

    import React from 'react';
    function HelloWorld() {
    return (
    <div>
        <h1>Hello World</h1>
    </div>
    );
    }
    export default HelloWorld;
    
                                    
  • # Install Bootstrap

    npm install bootstrap

    Optional (if you want to use bootstrap js components)
    npm install react-bootstrap
    Want to use any component like accordion first import
    import 'bootstrap/js/dist/accordion'

    (Then go to bootstrap official website copy accordion code and use)

    import React from 'react';
    import Accordion from 'react-bootstrap/Accordion';
    function BasicExample() {
    return (
    <Accordion defaultActiveKey="0">
        <Accordion.Item eventKey="0">
            <Accordion.Header>Accordion Item #1</Accordion.Header>
            <Accordion.Body>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                minim veniam, quis nostrud exercitation ullamco laboris nisi ut
                aliquip ex ea commodo consequat. Duis aute irure dolor in
                reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
                pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
                culpa qui officia deserunt mollit anim id est laborum.
            </Accordion.Body>
        </Accordion.Item>
        <Accordion.Item eventKey="1">
            <Accordion.Header>Accordion Item #2</Accordion.Header>
            <Accordion.Body>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                minim veniam, quis nostrud exercitation ullamco laboris nisi ut
                aliquip ex ea commodo consequat. Duis aute irure dolor in
                reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
                pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
                culpa qui officia deserunt mollit anim id est laborum.
            </Accordion.Body>
        </Accordion.Item>
    </Accordion>
    );
    }
    export default BasicExample;
    
                                    
  • # Install Swiper Slider

    npm install swiper

    For More Details Check Official Website
    https://swiperjs.com/react

    import React from 'react';
    import { Swiper, SwiperSlide } from 'swiper/react';
    import 'swiper/swiper-bundle.css';
    function HelloWorld() {
    return (
    <Swiper spaceBetween={50} slidesPerView={3} onSlideChange={()=> console.log('slide change')}
        onSwiper={(swiper) => console.log(swiper)}
        >
        <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
        <SwiperSlide>Slide 3</SwiperSlide>
        <SwiperSlide>Slide 4</SwiperSlide>
    </Swiper>
    );
    }
    export default HelloWorld;
    
                                        
  • # Install AOS Animation in React

    npm install aos
    AOS allows you to animate elements as you scroll down, and up. If you scroll back to top, elements will animate to it's previous state and are ready to animate again if you scroll down.

    import React, { useEffect } from 'react';
    import AOS from 'aos';
    import 'aos/dist/aos.css';
    
    
    const AOSAnimate = () => {
    useEffect(() => {
    AOS.init({
    duration: 1000,
    easing: 'ease-in-out',
    });
    }, []);
    
    
    return (
    <div>
        <div data-aos="fade-up" data-aos-duration="1000">
            <h1>Content to animate</h1>
        </div>
    </div>
    );
    };
    
    
    export default AOSAnimate;
    
    
                                    
  • # How to add Image

    If we want to use images from public folder then usie the following paths
    a). For Components
    /images/[image_name]
    b). For CSS
    ../../../public/images/[image_name]
    Set “../” according to your folder structure.

    import React from 'react';
    import logo from './assets/logo.svg';
    function App() {
    return (
    <div className="App">
        <img src={logo} className="logoReact" />
    </div>
    );
    }
    export default App;
    
    
                                    
  • # How to Use Routers

    To create routes and navigation for multiple pages in a React application, you typically use a library like React Router. React Router allows you to define routes and handle navigation between different components/pages in your application.

    npm install react-router-dom
    When we build multi page website so don’t do anything in app.js & index.js
    In app.js we create routes for all pages. See example below for better understanding

    Note: You need to create components for all pages then import in app.jsx and create routes for all

    import React from 'react';
    // Import Browser Route
    import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
    
    
    // Import All Pages
    import Home from './inc/pages/HomePage';
    import About from './inc/pages/AboutPage';
    import Contact from './inc/pages/ContactPage';
    import Services from './inc/pages/ServicesPage';
    import NotFound from './inc/pages/NotFound';
    
    
    function App() {
    return (
    <div className="App">
        <Router>
            <div>
                {/* Create Slugs using Routes */}
                <Routes>
                    <Route exact path="/" element={} />
                    <Route path="/about" element={} />
                    <Route path="/contact" element={} />
                    <Route path="/services" element={} />
                    <Route path="*" element={} />
                </Routes>
            </div>
        </Router>
    </div>
    );
    }
    export default App;
    
                                    
  • # Install Axios and usage

    npm install axios
    Here we use useEffect hook. The useEffect hook is a React hook that allows you to perform side effects in function components. Side effects include things like data fetching, subscriptions, or manually changing the DOM.

    If want to append data in DOM from API Response See Folowing Example

    import HeaderComp from '../components/Header';
    import React, { useEffect , useState } from 'react';
    import axios from 'axios';
    
    
    const ServicesPage = () => {
    const [dataMy, setData] = useState(null);
    useEffect(() => {
    const fetchData = async () => {
    try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log(response.data);
    setData(response.data)
    } catch (error) {
    console.error('Error fetching data:', error);
    }
    };
    fetchData();
    }, []);
    return (
    <div>
        <HeaderComp />
        {dataMy ? ( // Check if data is not null before rendering
        <ul>
            {dataMy.map(item => (
            <li key={item.id}>{item.title}</li>
            ))}
        </ul>
        ) : (
        <p>Loading...</p>
        )}
        <h1>Services</h1>
    </div>
    );
    };
    export default ServicesPage;
    
                                    
  • # Install Hemlet for SEO

    npm install react-helmet-async

    //Put the following code in index.js or the main entry file of your app:
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { HelmetProvider } from 'react-helmet-async';
    import App from './App';
    ReactDOM.render(
    <HelmetProvider>
        <App />
    </HelmetProvider>,
    document.getElementById('root')
    );
    
    
    //Put following code in all of your pages {page-name}.js
    
    import React from 'react';
    import { Helmet } from 'react-helmet-async';
    function HomePage() {
    return (
    <div>
        <Helmet>
            <title>Home Page - Your Site</title>
            <meta name="description" content="This is the homepage of Your Site." />
            <link rel="canonical" href="https://yoursite.com/home" />
        </Helmet>
        <h1>Welcome to the Home Page</h1>
    </div>
    );
    }
    export default HomePage;
    
                                    
  • # Fetch data using Wordpress API’s

    This code is according to axios so make sue Axios is install in your react app

    {SiteUrl}/wp-json/wp/v2/pages/
    {SiteUrl}/wp-json/wp/v2/pages/21 (specific page)
    {SiteUrl}/wp-json/wp/v2/posts/
    {SiteUrl}/wp-json/wp/v2/posts/21 (specific post)
    {SiteUrl}/wp-json/wp/v2/{custom_post_type}/
    {SiteUrl}/wp-json/wp/v2/media
    {SiteUrl}/wp-json/wp/v2/media?parent=11 (specific media)
    {SiteUrl}/wp-json/wp/v2/event/?slug=friday-night (for single blog post just pass the slug name as a query string)

    //In following code we are trying to fetch home page acf content.
    
    import React, { useEffect , useState } from 'react';
    import axios from 'axios';
    
    // Import Components
    import Banner from '../components/HomeBanner';
    import BannerSlider from '../components/HomeBannerSlider';
    import About from '../components/AboutSection';
    
    function Home() {
    const [acfData, setAcfData] = useState(null);
    // fetch data from wordpress
    useEffect(() => {
    const fetchData = async () => {
    try {
    const response = await axios.get('YourSiteUrl/wp-json/wp/v2/pages/'); // http://bookmyevents.wp/wp-json/wp/v2/pages/
    // Find the object with title "Home Page"
    const homePage = response.data.find(item => item.title && item.title.rendered === "Home Page");
    
    if (homePage && homePage.acf) {
    // Store the acf data in state
    setAcfData(homePage.acf);
    } else {
    console.log("No ACF data found for home page");
    }
    } catch (error) {
    console.error('Error fetching data:', error);
    }
    };
    fetchData();
    }, []);
    return (
    <>
        <div>
            {acfData && acfData.sections && acfData.sections.map((section, index) => {
            // You can add logic to render different components based on the section type
            switch (section.acf_fc_layout) {
            case 'main_banner':
            // return
            <Banner key={index} props={section} pageId={pageId} />;
            return
            <BannerSlider key={index} props={section} />;
            case 'about':
            return
            <About key={index} props={section} />;
            // Add more case blocks for other section types as needed
            default:
            return null;
            }
            })}
        </div>
    </>
    );
    }
    export default Home;
    
    //Banner Component
    
    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    
    
    function HomeBanner({ props }) {
    const [backgroundImage, setBackgroundImage] = useState(null);
    const bannerImageId = props.banner_bg;
    useEffect(() => {
    // following code is to fetch the banner image using page id and image id
    const fetchData = async () => {
    try {
    const response = await axios.get(`http://bookmyevents.wp/wp-json/wp/v2/media/${bannerImageId}`);
    // Find the media item with the specified ID
    if (response.data.guid.rendered) {
    setBackgroundImage(response.data.guid.rendered); // Set the image URL
    } else {
    console.warn("Media not found for banner_bg:", props.banner_bg);
    }
    } catch (error) {
    console.error('Error fetching data:', error);
    }
    };
    fetchData();
    }, [props]);
    return (
    <section className="bannerSection" style={{ backgroundImage: `url(${backgroundImage})` }}>
        <div className="container">
            <div className="row">
                <div className="col-12">
                    <h1>{props.banner_heading}</h1>
                    <p>{props.banner_description}</p>
                </div>
            </div>
        </div>
    </section>
    );
    }
    export default HomeBanner;
    
    
    // In following code we are trying to fetch gallerie in pages.
    
    
    import React, { useEffect, useState } from 'react';
    import axios from 'axios';
    
    
    function HomeBannerSlider({ props }) {
    const [MediaItem, setMediaItems] = useState([]);
    const bannerIds = props.banner_gallery;
    useEffect(() => {
    const fetchAllMedia = async () => {
    try {
    // Use Promise.all to fetch all media items
    const responses = await Promise.all(
    bannerIds.map((bannerId) =>
    axios.get(`http://bookmyevents.wp/wp-json/wp/v2/media/${bannerId}`)
    )
    );
    // Extract the data from each response and update state
    const items = responses.map((response) => response.data);
    setMediaItems(items);
    } catch (error) {
    console.error("Error fetching data:", error);
    }
    };
    fetchAllMedia();
    }, [bannerIds]);
    return (
    <section className="bannerSection">
        <div className="container">
            <div className="row">
                <div className="col-12">
                    <h1>{props.banner_heading}</h1>
                    <p>{props.banner_description}</p>
                    {MediaItem.map((item) => (
                    <img key={item.id} src={item.guid.rendered} alt={`Media ID ${item.id}`} />
                    ))}
                </div>
            </div>
        </div>
    </section>
    );
    }
    export default HomeBannerSlider;
    
                                    
  • # Basic Form using Spread Operator and console the values

    //Basic Form using Spread Operator and console the values
    import React, { useState } from 'react';
    
    
    function Contact() {
    const [getInputValues, holdInputValues] = useState({
    fName : '',
    lName : '',
    eMail : '',
    pHone : ''
    });
    const GetInputEvent = (event) => {
    const {name, value} = event.target;
    holdInputValues((prevVal) => {
    //console.log(prevVal);
    return{
    ...prevVal,
    [name]: value,
    }
    })
    }
    const onSubmitForm = (event) =>{
    event.preventDefault();
    console.log(getInputValues);
    }
    return (
    <>
        <section className="formContact">
            <div className="container">
                <div className="row">
                    <div className="col-md-7">
                        <form className="formWrapper" onSubmit={onSubmitForm}>
                            <div className="ap_form">
                                <h1>Hello</h1>
                                <input type="text" placeholder="Username" value={getInputValues.fName} name="fName"
                                    onChange={GetInputEvent} />
                                <input type="text" placeholder="Password" value={getInputValues.lName} name="lName"
                                    onChange={GetInputEvent} />
                                <input type="email" placeholder="Email" value={getInputValues.eMail} name="eMail"
                                    onChange={GetInputEvent} />
                                <input type="tel" placeholder="Phone" value={getInputValues.pHone} name="pHone"
                                    onChange={GetInputEvent} />
                                <button>Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </>
    );
    }
    export default Contact;
    
    
                                    
  • # Basic Form submission in cf7 wordpress using API’s and mails are sent

    import React, { useState } from 'react';
    import axios from 'axios';
    import GlobalComp from '../global/globalComponent';
    
    
    function Contact() {
    const [getInputValues, holdInputValues] = useState({
    fName : '',
    eMail : '',
    pHone : ''
    });
    const [responseMessage, setResponseMessage] = useState('');
    const GetInputEvent = (event) => {
    const {name, value} = event.target;
    holdInputValues((prevVal) => {
    //console.log(prevVal);
    return{
    ...prevVal,
    [name]: value,
    }
    })
    }
    const onSubmitForm = async (event) => {
    event.preventDefault();
    console.log(getInputValues);
    
    
    // Prepare the payload
    const payload = new FormData();
    payload.append('your-name', getInputValues.fName); // Replace 'your-name' with the CF7 field name
    payload.append('your-email', getInputValues.eMail); // Replace 'your-email' with the CF7 field name
    payload.append('your-phone', getInputValues.pHone); // Replace 'your-phone' with the CF7 field name
    payload.append('_wpcf7_unit_tag', 123);
    for (let pair of payload.entries()) {
    console.log(pair[0] + ": " + pair[1]);
    }
    try {
    const response = await axios.post(
    'http://bookmyevents.wp/wp-json/contact-form-7/v1/contact-forms/60/feedback',payload,{
    headers: {
    'Content-Type': 'multipart/form-data',
    },
    }
    );
    if (response.data.status === 'mail_sent') {
    setResponseMessage('Your message has been sent successfully!');
    holdInputValues({ fName: '', eMail: '', pHone: '' });
    } else {
    setResponseMessage('There was an issue sending your message. Please try again.');
    }
    } catch (error) {
    setResponseMessage('An error occurred. Please check your connection and try again.');
    console.error('Error sending the form:', error);
    }
    }
    return (
    <>
        <section className="formContact">
            <div className="container">
                <div className="row">
                    <div className="col-md-7">
                        <form className="formWrapper" onSubmit={onSubmitForm}>
                            <div className="ap_form">
                                <h1>Hello</h1>
                                <input type="text" placeholder="Username" value={getInputValues.fName} name="fName"
                                    onChange={GetInputEvent} />
                                <input type="email" placeholder="Email" value={getInputValues.eMail} name="eMail"
                                    onChange={GetInputEvent} />
                                <input type="tel" placeholder="Phone" value={getInputValues.pHone} name="pHone"
                                    onChange={GetInputEvent} />
                                <button>Submit</button>
                                {responseMessage && <p>{responseMessage}</p>}
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </>
    );
    }
    export default Contact;
    
    
                                    
  • # How to create single blog posts.

    Use the following api ke if you are using wordpess as a backend
    http://originalboommyevents.wp/wp-json/wp/v2/event/?slug=friday-night
    Pass the post slug in slug parameter

    //don't forget to import this in App.js or wherever you have written your routes
    import BlogPost from './BlogPost';
    
    // Put the following code in routes
    <Route path="/blog/:slug" element={<BlogPost />} />
    
    
    // Create a component for single blog posts
    
    import React from 'react';
    import { useParams } from 'react-router-dom';
    const BlogPost = () => {
    // Get the slug from the URL
    const { slug } = useParams();
    // Use the slug to fetch the blog post content (optional for API calls)
    // For now, just display the slug
    return (
    <div>
        <h1>Blog Post: {slug}</h1>
        <p>Content of the blog post goes here...</p>
    </div>
    );
    };
    export default BlogPost;