0

I want to make an input type global level so I created one component and i want to access it from another file. Here is an example...

Main File:

class User extends Component {

    constructor(props) {
        super(props);
    }
    render(){
       return (
                <CustomInput 
                    refval = "username"
                    label = "Username"
                    classNameLabel = "pl0"
                    icon = "person"
                />
       );
    }
}

Component File:

class CustomInput extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
      return (
          <div className="col-sm-3 mt10">
            <label className={"col-sm-12 "+this.props.classNameLabel}>{this.props.label}</label>
            <div className="col-sm-12 pl0">
                {(this.props.icon!=="" && 
                  <i className={"fa fa-"+this.props.icon+""}></i>
                )}
                <input type={this.props.type} ref={this.props.refval} className="form-control inputText" />
            </div>
          </div>
      );
    }
}

how I can archive this? Thank you so much in Advance :)

Shubham Khuva
  • 13
  • 1
  • 9
  • Hello, this article should help you https://pl.reactjs.org/docs/forwarding-refs.html – Maciej Trzciński Feb 26 '20 at 11:26
  • Add an event like onKeyDown that means when you type something and press enter then you can fire a function and there you can get the value and pass it in props or use redux. – Juhil Somaiya Feb 26 '20 at 11:31
  • Check out this stackoverflow post https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs. This explains how to pass a function from parent to child and retrieve data from child. – nbsamurai Feb 26 '20 at 11:35

1 Answers1

0

One way is to pass a function down, like this:

class User extends Component {
    constructor(props) {
        super(props);
    }

    const onClick =(e) => { /// do stuff}
    render(){
    return (
        <CustomInput 
        refval = "username"
        label = "Username"
        classNameLabel = "pl0"
        icon = "person" onClick={onClick} />
    }}
}  

Access the callback via props

class CustomInput extends React.Component {
        constructor(props) {
            super(props);
        }
        render() {
            return (
                    <input type={this.props.type} onClick={props.OnClick} />
                </div>
                </div>
            );
        }
    }

A better approach may be to look into hooks and accessing global user state. Another tip you can write these components as functional rather than class components

Jon Jones
  • 1,014
  • 1
  • 9
  • 17