react-spring#Spring JavaScript Examples

The following examples show how to use react-spring#Spring. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PaymentConfirmed.js    From web with MIT License 6 votes vote down vote up
render() {
    const { isVisible } = this.state;
    const { orderData } = this.props;

    return (
      <>
        <Spring
          native
          from={{ opacity: 0 }}
          to={{ opacity: isVisible ? 1 : 0 }}>
          {stylesProps => (
            <animated.div style={stylesProps}>
              <Result>
                <i className="fas fa-check-circle" />
                <h3 className="is-size-5 is-uppercase	has-text-weight-bold">
                  Payment complete
                </h3>
                <p className="info">
                  Order code is <OrderId>#{orderData.orderId}</OrderId>
                  <br />
                  Please check your email
                  <br />
                  for delivery updates.
                </p>
              </Result>
              <BuyBtn
                to="/"
                className="button is-dark is-large is-radiusless is-uppercase">
                Continue Shopping
              </BuyBtn>
            </animated.div>
          )}
        </Spring>
      </>
    );
  }
Example #2
Source File: ProductGallery.js    From web with MIT License 5 votes vote down vote up
render() {
    const { isVisible } = this.state;
    const { variant } = this.props;

    const isMobile = !isUndefined(global.window)
      ? global.window.innerWidth < 768
      : false;

    // console.log('images', product.variant.images);
    const images = variant.images
      ? variant.images.map(image => ({
          original: image.asset.fluid.src,
          thumbnail: image.asset.fluid.src,
        }))
      : [];
    // console.log('images 2', images);

    return (
      <Container>
        <Spring
          native
          from={{ opacity: 0, marginLeft: -100 }}
          to={{
            opacity: isVisible ? 1 : 0,
            marginLeft: isVisible ? 0 : -100,
          }}
        >
          {styles => (
            <animated.div style={styles}>
              <ImageGallery
                items={images}
                thumbnailPosition="bottom"
                showPlayButton={false}
                showNav={false}
                showThumbnails={!isMobile}
                showFullscreenButton={!isMobile}
                showBullets={isMobile}
                lazyLoad
              />
            </animated.div>
          )}
        </Spring>
      </Container>
    );
  }
Example #3
Source File: CartSteps.js    From web with MIT License 4 votes vote down vote up
CartSteps = () => {
  const [country, setCountry] = useState('India');
  const [loading, setLoading] = useState(false);
  const [activeStep, setActiveStep] = useState(1);
  const [userData, setUserData] = useState({});
  const [paymentData, setPaymentData] = useState({});
  const [orderData, setOrderData] = useState({});
  const [discount, setDiscount] = useState(0);
  const cartItems = useStoreState(state => state.cart.items);
  const location = useStoreState(state => state.user.location);
  const emptyCart = useStoreActions(actions => actions.cart.empty);
  const [createOrder, { data: createOrderResult }] = useMutation(
    createOrderMutation,
  );
  const [updateOrder] = useMutation(updateOrderMutation);
  const [verifyCard, { data: verifyCardResult }] = useMutation(
    verifyCardMutation,
  );
  // console.log('data', data, verifyCardResult, createOrderResult);

  useEffect(() => {
    if (location && location.country) {
      setCountry(location.country);
    }
  }, [location]);

  const handleCreateOrder = async gateway => {
    const tokenId = verifyCardResult ? verifyCardResult.verifyCard.id : '';
    const orderId = randomstring.generate(6).toUpperCase();
    const { email, fullName, ...address } = userData;
    const products = cartItems.map(item => {
      return { id: item.id, sku: item.sku };
    });
    const inputData = {
      tokenId,
      orderId,
      customer: { email, fullName, address: { ...address } },
      products,
      discount,
      country: location.country,
      currencyCode: location.currencyCode,
    };

    await createOrder({
      variables: {
        input: inputData,
        gateway,
      },
    });
  };

  const finishOrder = () => {
    // ReactGA.plugin.execute('ecommerce', 'addTransaction', {
    //   id: createOrderResult.createOrder.orderId,
    //   name: 'test checkout', // Product name. Required.
    //   sku: 'DD23444', // SKU/code.
    //   category: 'Party Toys', // Category or variation.
    //   price: '11.99', // Unit price.
    //   quantity: '1', // Quantity.
    // });
    // ReactGA.plugin.execute('ecommerce', 'send');
    // ReactGA.plugin.execute('ecommerce', 'clear');

    setOrderData(createOrderResult.createOrder);
    setActiveStep(4);
    emptyCart();
  };

  useEffect(() => {
    // make verifyCard mutation to generate token
    if (!isEmpty(paymentData)) {
      verifyCard({ variables: { input: paymentData } });
    }
  }, [paymentData]);

  useEffect(() => {
    if (!verifyCardResult) {
      return;
    }
    handleCreateOrder('stripe');
  }, [verifyCardResult]);

  useEffect(() => {
    // console.log('now show success', createOrderResult);
    if (!createOrderResult) {
      return;
    }

    if (country === 'India') {
      // use razor pay
      const options = {
        key: config.razorPayKey, // Enter the Key ID generated from the Dashboard
        amount: `${createOrderResult.createOrder.total}00`,
        currency: 'INR',
        name: config.siteName,
        description: config.description,
        image: config.logo,
        order_id: createOrderResult.createOrder.paymentId, // This is a sample Order ID. Create an Order using Orders API. (https://razorpay.com/docs/payment-gateway/orders/integration/#step-1-create-an-order). Refer the Checkout form table given below
        handler() {
          // do mutation to update payment ID and payment status to success
          updateOrder({
            variables: {
              input: {
                orderId: createOrderResult.createOrder.orderId,
                status: 'paid',
              },
            },
          });
          finishOrder();
        },
        prefill: {
          name: userData.fullName,
          email: userData.email,
          contact: userData.telephone,
        },
        notes: {
          address: userData.address,
        },
        theme: {
          color: theme.mainBrandColor,
        },
      };
      const rzp1 = new Razorpay(options);
      rzp1.open();
      setLoading(false);
    } else {
      finishOrder();
    }
  }, [createOrderResult]);

  useEffect(() => {
    if (!isEmpty(userData) && country === 'India') {
      handleCreateOrder('razorpay');
    }
  }, [userData]);

  return (
    <section className="section">
      <div className="container">
        <Heading>Cart</Heading>
        <Spring
          native
          from={{ opacity: 0 }}
          to={{
            opacity: activeStep !== 1 ? 1 : 0,
            // eslint-disable-next-line prettier/prettier
          }}
        >
          {styles => (
            <animated.div style={styles}>
              <CheckoutProgress activeStep={activeStep} />
            </animated.div>
          )}
        </Spring>
        <div className="columns">
          <Spring
            native
            from={{ marginLeft: '25%' }}
            // eslint-disable-next-line prettier/prettier
            to={{ marginLeft: activeStep === 1 ? '25%' : '0%' }}
          >
            {stylesProps => (
              <animated.div
                style={stylesProps}
                // eslint-disable-next-line prettier/prettier
                className="column section is-half is-hidden-mobile"
              >
                <CartItems
                  cartItems={cartItems}
                  showCheckoutBtn={activeStep === 1}
                  discount={discount}
                  setDiscount={setDiscount}
                  handlePayment={() => {
                    setActiveStep(2);
                  }}
                />
              </animated.div>
            )}
          </Spring>
          <div
            className={`column section ${
              activeStep === 2 ? 'is-hidden-mobile' : ''
            } is-hidden-tablet`}
          >
            <CartItems
              cartItems={cartItems}
              showCheckoutBtn={activeStep === 1}
              discount={discount}
              setDiscount={setDiscount}
              handlePayment={() => {
                setActiveStep(2);
              }}
            />
          </div>
          <div className="column section">
            {activeStep === 2 && (
              <CheckoutForm
                enableReinitialize
                initialValues={{ country: location.country }}
                loading={loading}
                handlePayment={data2 => {
                  setLoading(true);
                  if (country === 'India') {
                    // razorpay payment
                    setUserData(data2);
                  } else {
                    // stripe payment
                    setActiveStep(3);
                    setUserData(data2);
                  }
                }}
              />
            )}
            {activeStep === 3 && (
              <PaymentForm
                handlePayment={data2 => {
                  setPaymentData(data2);
                }}
              />
            )}
            {activeStep === 4 && <PaymentConfirmed orderData={orderData} />}
          </div>
        </div>
      </div>
    </section>
  );
}
Example #4
Source File: CheckoutForm.js    From web with MIT License 4 votes vote down vote up
render() {
    const { isVisible } = this.state;
    const {
      values,
      touched,
      errors,
      isSubmitting,
      handleSubmit,
      handleChange,
      handleBlur,
      loading,
    } = this.props;

    return (
      <>
        <Spring
          native
          from={{ opacity: 0 }}
          to={{ opacity: isVisible ? 1 : 0 }}
        >
          {stylesProps => (
            <animated.div style={stylesProps}>
              <Heading className="is-size-5">Shipping address</Heading>
              <form onSubmit={handleSubmit}>
                <div className="field">
                  <label className="label">Full name</label>
                  <div className="control">
                    <input
                      className="input is-shadowless"
                      name="fullName"
                      value={values.fullName}
                      onChange={handleChange}
                      onBlur={handleBlur}
                      autoFocus
                    />
                    {errors.fullName && touched.fullName && (
                      <p className="help is-danger">{errors.fullName}</p>
                    )}
                  </div>
                </div>
                <div className="field">
                  <label className="label">Address Line 1</label>
                  <div className="control">
                    <input
                      className="input is-shadowless"
                      name="addressLine1"
                      value={values.addressLine1}
                      onChange={handleChange}
                      onBlur={handleBlur}
                    />
                    {errors.addressLine1 && touched.addressLine1 && (
                      <p className="help is-danger">{errors.addressLine1}</p>
                    )}
                  </div>
                </div>
                <div className="field">
                  <label className="label">Address Line 2</label>
                  <div className="control">
                    <input
                      className="input is-shadowless"
                      name="addressLine2"
                      value={values.addressLine2}
                      onChange={handleChange}
                      onBlur={handleBlur}
                    />
                    {errors.addressLine2 && touched.addressLine2 && (
                      <p className="help is-danger">{errors.addressLine2}</p>
                    )}
                  </div>
                </div>
                <div className="field is-horizontal">
                  <div className="field-body">
                    <div className="field">
                      <label className="label">City</label>
                      <div className="control">
                        <input
                          className="input is-shadowless"
                          name="city"
                          value={values.city}
                          onChange={handleChange}
                          onBlur={handleBlur}
                        />
                        {errors.city && touched.city && (
                          <p className="help is-danger">{errors.city}</p>
                        )}
                      </div>
                    </div>
                    <div className="field">
                      <label className="label">Postcode</label>
                      <div className="control">
                        <input
                          className="input is-shadowless"
                          name="postcode"
                          value={values.postcode}
                          onChange={handleChange}
                          onBlur={handleBlur}
                        />
                        {errors.postcode && touched.postcode && (
                          <p className="help is-danger">{errors.postcode}</p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="field is-horizontal">
                  <div className="field-body">
                    <div className="field">
                      <label className="label">State</label>
                      <div className="control">
                        <input
                          className="input is-shadowless"
                          name="state"
                          value={values.state}
                          onChange={handleChange}
                          onBlur={handleBlur}
                        />
                        {errors.state && touched.state && (
                          <p className="help is-danger">{errors.state}</p>
                        )}
                      </div>
                    </div>
                    <div className="field">
                      <label className="label">Country</label>
                      <div className="control">
                        <div className="select" name="country">
                          <select
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.country}
                          >
                            <option>Select dropdown</option>
                            {countries.map(country => (
                              <option key={country.code} value={country.name}>
                                {country.name}
                              </option>
                            ))}
                          </select>
                        </div>
                        {/* <input
                          className="input is-shadowless"
                          name="country"
                          value={values.country}
                          onChange={handleChange}
                          onBlur={handleBlur}
                        /> */}
                        {errors.country && touched.country && (
                          <p className="help is-danger">{errors.country}</p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="field">
                  <label className="label">Email</label>
                  <div className="control">
                    <input
                      className="input is-shadowless"
                      name="email"
                      value={values.email}
                      onChange={handleChange}
                      onBlur={handleBlur}
                    />
                    {errors.email && touched.email && (
                      <p className="help is-danger">{errors.email}</p>
                    )}
                  </div>
                </div>
                <div className="field">
                  <label className="label">Telephone</label>
                  <div className="control">
                    <input
                      className="input is-shadowless"
                      name="telephone"
                      value={values.telephone}
                      onChange={handleChange}
                      onBlur={handleBlur}
                    />
                    {errors.telephone && touched.telephone && (
                      <p className="help is-danger">{errors.telephone}</p>
                    )}
                  </div>
                </div>
                <BuyBtn
                  type="submit"
                  disabled={isSubmitting || loading}
                  className={`checkout-form-btn button is-dark is-large is-radiusless is-uppercase ${
                    isSubmitting || loading ? 'is-loading' : ''
                  }`}
                >
                  <span className="icon">
                    <i className="far fa-credit-card" />
                  </span>
                  <span>Make payment</span>
                </BuyBtn>
              </form>
            </animated.div>
          )}
        </Spring>
      </>
    );
  }
Example #5
Source File: PaymentForm.js    From web with MIT License 4 votes vote down vote up
render() {
    const { isVisible } = this.state;
    const {
      values,
      touched,
      errors,
      isSubmitting,
      handleSubmit,
      handleChange,
      handleBlur,
    } = this.props;

    return (
      <>
        <Spring
          native
          from={{ opacity: 0 }}
          to={{ opacity: isVisible ? 1 : 0 }}>
          {stylesProps => (
            <animated.div style={stylesProps}>
              <Cards className="has-text-centered">
                <img src="/images/payment-strip.png" alt="payments cards" />
              </Cards>
              <p className="has-text-grey is-size-7	has-text-centered">
                All transactions are secure and encrypted. Credit card
                information is never stored.
              </p>
              <br />
              <form onSubmit={handleSubmit}>
                <div className="field">
                  <label className="label">Card number</label>
                  <div className="control">
                    <Cleave
                      className="input is-shadowless"
                      name="cardNumber"
                      id="card-number"
                      value={values.cardNumber}
                      onChange={handleChange}
                      onBlur={handleBlur}
                      options={{ creditCard: true }}
                    />
                    {errors.cardNumber && touched.cardNumber && (
                      <p className="help is-danger">{errors.cardNumber}</p>
                    )}
                  </div>
                </div>
                <div className="field is-horizontal">
                  <div className="field-body">
                    <div className="field">
                      <label className="label">Expiry Month</label>
                      <div className="control">
                        <Cleave
                          className="input is-shadowless"
                          name="expMonth"
                          value={values.expMonth}
                          onChange={handleChange}
                          onBlur={handleBlur}
                          options={{
                            date: true,
                            datePattern: ['m'],
                          }}
                        />
                        {errors.expMonth && touched.expMonth && (
                          <p className="help is-danger">{errors.expMonth}</p>
                        )}
                      </div>
                    </div>
                    <div className="field">
                      <label className="label">Expiry Year</label>
                      <div className="control">
                        <Cleave
                          className="input is-shadowless"
                          name="expYear"
                          value={values.expYear}
                          onChange={handleChange}
                          onBlur={handleBlur}
                          options={{
                            date: true,
                            datePattern: ['Y'],
                          }}
                        />
                        {errors.expYear && touched.expYear && (
                          <p className="help is-danger">{errors.expYear}</p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="field">
                  <label className="label">CVC</label>
                  <div className="control">
                    <Cleave
                      className="input is-shadowless"
                      name="cvc"
                      value={values.cvc}
                      onChange={handleChange}
                      onBlur={handleBlur}
                      maxLength={3}
                      options={{
                        numeral: true,
                      }}
                    />
                    {errors.cvc && touched.cvc && (
                      <p className="help is-danger">{errors.cvc}</p>
                    )}
                  </div>
                </div>
                <BuyBtn
                  className="payment-form-btn button is-dark is-large is-radiusless is-uppercase"
                  onClick={this.handleSubmit}
                  disabled={isSubmitting}>
                  <span className="icon">
                    <i className="fas fa-lock" />
                  </span>
                  <span>Finish and Pay</span>
                </BuyBtn>
              </form>
            </animated.div>
          )}
        </Spring>
      </>
    );
  }
Example #6
Source File: ProductInfo.js    From web with MIT License 4 votes vote down vote up
ProductInfo = ({ product, home, reviews, variant, setVariant }) => {
  const [isVisible, setIsVisible] = useState(false);
  const location = useStoreState(state => state.user.location);
  const addToCart = useStoreActions(actions => actions.cart.add);
  // console.log('product', product);

  useEffect(() => {
    setTimeout(() => {
      setIsVisible(true);
    }, 400);
  }, []);

  const metaUrl = `${config.siteUrl}/product/${product.slug.current}`;
  const metaTitle = `Checkout ${product.title} at ${config.siteName}`;

  const handleAddToCart = () => {
    const price = getPrice(variant.pricing, true, location);
    ReactGA.plugin.execute('ecommerce', 'addItem', {
      id: product._id,
      title: product.title,
      sku: variant.sku || '-',
      price,
      // category: 'Cases',
      quantity: '1',
    });

    const itemData = {
      itemId: makeId(5),
      id: product._id,
      title: product.title,
      slug: product.slug.current,
      shippingCost: getPrice(product.shippingCost, false, location),
      sku: variant.sku,
      price,
      image: variant.featuredImage.asset.fluid.src,
      color: variant.color ? variant.color.hex : '',
      quantity: 1,
    };
    addToCart(itemData);

    setTimeout(() => navigateTo('/cart'), 600);
  };

  return (
    <>
      <RatingContainer>
        <i className="fas fa-star" />
        <i className="fas fa-star" />
        <i className="fas fa-star" />
        <i className="fas fa-star" />
        <i className="fas fa-star" />
        <span>{reviews.length} Reviews</span>
      </RatingContainer>
      <Heading centered>{product.title}</Heading>
      <Price className="has-text-weight-semibold has-text-centered">
        <CurrencyFormat pricing={variant.pricing} isDiscount />{' '}
        {variant.discountPrice < variant.price && (
          <span>
            <CurrencyFormat pricing={variant.pricing} />
          </span>
        )}
      </Price>
      <Spring native from={{ opacity: 0 }} to={{ opacity: isVisible ? 1 : 0 }}>
        {stylesProps => (
          <animated.div style={stylesProps}>
            <Variants>
              {product.otherVariants &&
                product.otherVariants.map(variantItem => {
                  return variantItem.color ? (
                    <VariantColor
                      key={variantItem.color.hex}
                      color={variantItem.color.hex}
                      active={
                        variant.color
                          ? variant.color.hex === variantItem.color.hex
                          : false
                      }
                      onClick={() => setVariant(variantItem)}
                    />
                  ) : null;
                })}
            </Variants>
            <BuyBtn
              className="product-info-btn button is-dark is-medium is-radiusless is-uppercase"
              // eslint-disable-next-line prettier/prettier
              onClick={() => handleAddToCart()}
            >
              Add to cart
            </BuyBtn>
            <ShippingInfo>Free Shipping to {location.country}.</ShippingInfo>
            <AccordionStyled>
              <AccordionItem expanded>
                <AccordionItemTitle>
                  <h3>Product Details</h3>
                </AccordionItemTitle>
                <AccordionItemBody>
                  {product._rawBody && (
                    <BlockContent blocks={product._rawBody.en || []} />
                  )}
                  <p>Made in India</p>
                  <p>All prices include sales taxes.</p>
                </AccordionItemBody>
              </AccordionItem>
              <AccordionItem>
                <AccordionItemTitle>
                  <h3>Delivery & Returns</h3>
                </AccordionItemTitle>
                <AccordionItemBody>
                  <ReactMarkdown source={home.productDeliveryInfo} />
                  <br />
                  <ReactMarkdown source={home.productShippingReturns} />
                </AccordionItemBody>
              </AccordionItem>
            </AccordionStyled>
            <ShareContainer>
              <h3>Share</h3>
              <div className="share-icons">
                <div className="level">
                  <div className="level-item">
                    <FacebookShareButton
                      url={metaUrl}
                      quote={metaTitle}
                      hashtag="#ecommerce"
                    >
                      <i className="fab fa-facebook-square" />
                    </FacebookShareButton>
                  </div>
                  <div className="level-item">
                    <TwitterShareButton
                      url={metaUrl}
                      title={metaTitle}
                      hashtags={['ecommerce']}
                    >
                      <i className="fab fa-twitter-square" />
                    </TwitterShareButton>
                  </div>
                  <div className="level-item">
                    <EmailShareButton url={metaUrl} subject={metaTitle}>
                      <i className="fas fa-envelope" />
                    </EmailShareButton>
                  </div>
                </div>
              </div>
            </ShareContainer>
          </animated.div>
        )}
      </Spring>
    </>
  );
}
Example #7
Source File: index.jsx    From react-animated-numbers with MIT License 4 votes vote down vote up
AnimatedNumber = ({
  animateToNumber,
  fontStyle,
  configs,
  includeComma,
}) => {
  const { ref, inView } = useInView({ triggerOnce: true });
  const keyCount = React.useRef(0);
  const animteTonumberString = includeComma
    ? Math.abs(animateToNumber).toLocaleString()
    : String(Math.abs(animateToNumber));
  const animateToNumbersArr = Array.from(animteTonumberString, Number).map(
    (x, idx) => (isNaN(x) ? animteTonumberString[idx] : x)
  );

  const [numberHeight, setNumberHeight] = React.useState(0);

  const numberDivRef = React.useRef(null);

  const setConfig = (configs, number, index) => {
    if (typeof configs === "function") {
      return configs(number, index);
    }
    return configs
      ? configs[getRandomIntInclusive(0, configs.length - 1)]
      : undefined;
  };

  React.useEffect(() => {
    const height = numberDivRef.current.getClientRects()?.[0]?.height;
    if (height) {
      setNumberHeight(height);
    }
  }, [animateToNumber, fontStyle]);

  return (
    <>
      {numberHeight !== 0 && (
        <div
          ref={ref}
          style={{ display: "flex", flexDirection: "row" }}
          className="animated-container"
        >
          {inView && animateToNumber < 0 && <div style={fontStyle}>-</div>}
          {inView &&
            animateToNumbersArr.map((n, index) => {
              if (typeof n === "string") {
                return (
                  <div key={index} style={{ ...fontStyle }}>
                    {n}
                  </div>
                );
              }

              return (
                <div
                  key={index}
                  style={{
                    height: numberHeight,
                    overflow: "hidden",
                  }}
                >
                  <Spring
                    key={`${keyCount.current++}`}
                    from={{
                      transform: "translateY(0px)",
                    }}
                    to={{
                      transform: `translateY(${
                        -1 * (numberHeight * animateToNumbersArr[index]) -
                        numberHeight * 20
                      })`,
                    }}
                    config={setConfig(configs, n, index)}
                  >
                    {(props) =>
                      NUMBERS.map((number, i) => (
                        <animated.div
                          key={i}
                          style={{ ...fontStyle,...props }}
                        >
                          {number}
                        </animated.div>
                      ))
                    }
                  </Spring>
                </div>
              );
            })}
        </div>
      )}

      <div
        ref={numberDivRef}
        style={{ position: "absolute", top: -9999, ...fontStyle }}
      >
        {0}
      </div>
    </>
  );
}