Home > OS >  How can I use a React component in other component?
How can I use a React component in other component?

Time:10-13

I have this component right here

Scanner.js

import React, { Component } from "react";
import { render } from "react-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";

function Scanner() {
  const [data, setData] = React.useState("Not Found");

  return (
    <>
      <BarcodeScannerComponent
        width={500}
        height={500}
        onUpdate={(err, result) => {
          if (result) setData(result.text);
          else setData("Not Found");
        }}
      />
      <p>{data}</p>
    </>
  );
}
export default Scanner;

I want to use this component inside of another Component, best would be on Button click.

Order.js

import React, { useState, useEffect } from "react";
import OrderDataService from "../services/OrderService";
import BarcodeScannerComponent from "react-qr-barcode-scanner";

const Order = (props) => {
  const initialOrderState = {
    id: null,
    costumer: "",
    palette: "",
    packaged: false,
  };

  const [currentOrder, setCurrentOrder] = useState(initialOrderState);
  const [message, setMessage] = useState("");
  const [results, setResults] = useState([]);

  const getOrder = (id) => {
    OrderDataService.get(id)
      .then((response) => {
        setCurrentOrder(response.data[0]);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  useEffect(
    (data) => {
      getOrder(props.match.params.id);
    },
    [props.match.params.id]
  );

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setCurrentOrder({ ...currentOrder, [name]: value });
  };

  const updatepackaged = (status) => {
    var data = {
      id: currentOrder.id,
      costumer: currentOrder.costumer,
      palette: currentOrder.palette,
      packaged: status,
    };

    OrderDataService.update(currentOrder.id, data)
      .then((response) => {
        setCurrentOrder({ ...currentOrder, packaged: status });
        console.log(response.data);
        setMessage("The status was updated successfully!");
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const updateOrder = () => {
    OrderDataService.update(currentOrder.id, currentOrder)
      .then((response) => {
        console.log(response.data);
        setMessage("The Order was updated successfully!");
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const deleteOrder = () => {
    OrderDataService.remove(currentOrder.id)
      .then((response) => {
        console.log(response.data);
        props.history.push("/Orders");
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const changePalette = () => {
    console.log("Palette");
  };

  return (
    <div>
      {currentOrder ? (
        <div className='edit-form'>
          <h4>Order</h4>
          <form>
            <div className='form-group'>
              <label htmlFor='costumer'>costumer</label>

              <input
                type='text'
                className='form-control'
                id='costumer'
                name='costumer'
                placeholder={currentOrder.costumer}
                value={currentOrder.costumer}
                onChange={handleInputChange}
              />
            </div>

            <div className='form-group'>
              <label htmlFor='palette'>Palette</label>
              <input
                type='text'
                className='form-control'
                id='palette'
                name='palette'
                placeholder={currentOrder.palette}
                value={currentOrder.palette}
                onChange={handleInputChange}
              />
              <Scanner/>
            </div>

            <div className='form-group'>
              <label>
                <strong>Status:</strong>
              </label>
              {currentOrder.packaged ? "packaged" : "Pending"}
            </div>
          </form>

          {currentOrder.packaged ? (
            <button
              className='badge badge-primary mr-2'
              onClick={() => updatepackaged(false)}
            >
              UnPublish
            </button>
          ) : (
            <button
              className='badge badge-primary mr-2'
              onClick={() => updatepackaged(true)}
            >
              Publish
            </button>
          )}

          <button className='badge badge-danger mr-2' onClick={deleteOrder}>
            Delete
          </button>

          <button
            type='submit'
            className='badge badge-success'
            onClick={updateOrder}
          >
            Update
          </button>
          <p>{message}</p>
        </div>
      ) : (
        <div>
          <br />
          <p>Please click on a Order...</p>
        </div>
      )}
    </div>
  );
};

export default Order;

But this is not possible because i am breaking the rules of Hooks in React. And for use, i have to use "data" from Scanner component and then send it to Order Component.

CodePudding user response:

Well, well! so now I understand what is the problem, first I think you have these 2 files in one component, if yes, it would be like this.

first, import your Scanner.js in the Order.js component. like this.

import Scanner from "./Scanner";

and then render it wherever you want in the order component, it would be like this.

 <div className='form-group'>
          <label htmlFor='palette'>Palette</label>
          <input
            type='text'
            className='form-control'
            id='palette'
            name='palette'
            placeholder={currentOrder.palette}
            value={currentOrder.palette}
            onChange={handleInputChange}
          />
          <Scanner/>
        </div>

that's it

Update 1

I see you have some problem with your code:

     <BarcodeScannerComponent
        width={500}
        height={500}
        onUpdate={(err, result) => {
          if (result) setData(result.text);
          else setData("Not Found"); // you don't need else in this position. it would be as follow.
         setData("Not Found");
        }}
      />

good luck:)

  • Related