简体   繁体   中英

How can I use a React component in other component?

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. 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.

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM