Home > database >  Button Event not worlking in react, passing forwaring ref
Button Event not worlking in react, passing forwaring ref

Time:05-24

I am working with react and react-bootstrap and react-select.

I have one issue, when I clicked the button its like not showing on console and not do any action.

The Input.js functional component is a child of Hero.js functional component.

So the hero.js is the parent component and Input.js is a child component.

And my button is in Parent component(Hero.js).

So I am using the forwarding ref to parent to child component on my button handler.

I am using react-select input in Input.js and I want to focus when button is clicked.

The console is also not showing on button clicked.

here is Hero.js (Parent component)

import React, { useState} from "react";
import "../App.css";
import Input from "./Input";
import Btnfill from "./Btnfill";

function Hero() {
  const [Infocus, setInfocus] = useState();


  const focusInput = () => {
       console.log(Infocus.current);
       Infocus.focus();
  }

  return (
    <>
              <Input
                icon={Search}
                cname={{ iconavailable: "input", noIcon: "input-notIcon" }}
                placeholder="Search Industries"
                ref={setInfocus}
              />
              <Btnfill text="Search" size="larger" onClick={focusInput} />
    </>
  );
}
export default Hero;

Here is Input.js

import React, { useState, useEffect} from "react";
import Select from "react-select";

const Input =  React.forwardRef((props, refrence) =>  {

// Input select options
  const options = [
    { value: "chocolate", label: "Chocolate" },
    { value: "strawberry", label: "Strawberry" },
    { value: "vanilla", label: "Vanilla" },
  ];

  return (
    <div>
<Select
        defaultValue={selectedOption}
        onChange={onChangeEvent}
        options={options}
        className={props.icon ? props.cname.iconavailable : props.cname.noIcon}
        placeholder={props.placeholder}
        ref={refrence}
      />
</div>
  );
})

export default Input;

CodePudding user response:

You want to use ref, but what you actually do in your Hero.js is - you are defining state and pass down the set-state function down.

What you instead need to do:

  • Define new ref in Hero.jsx: const inputRef = useRef();
  • In your on button click handler set the focus. To do so, you need to access the current property of the ref: const focusInput = () => inputRef.current.focus();
  • Pass down ref instead: <Input ... ref={inputRef} />

https://codesandbox.io/s/nervous-lewin-8510tf

  • Related