score:2

Accepted answer

if i´m reading correctly you want to access the input element from the parent component?

you have to use another name for your prop as ref is a keyword prop which will automatically assign the component the given variable.

<childcomponent inputref={this.setref} handlechange={this.handlechange.bind(this)}/>

class childcomponent extends component {
    render() {
        return(
            <input type="text" ref={this.props.inputref} onchange= {this.props.handlechange.bind(this)} > </input>
        );
    }
}

based on how you want to access the ref you can either set this.refs directly to the prop or set it inside your setref function.

// either `this.refs` and then usable through `this.refs.current`
<childcomponent inputref={this.refs} {...} />

// or `this.setref` and assign it yourself
setref = (ref) => {this.refs = ref;}

score:0

ref work only on native dom element, to make ref work on user defined component, you need this:

https://reactjs.org/docs/forwarding-refs.html

score:2

ref(as well as key btw) is very special prop. it is not accessible in child by this.props.ref.

shortest way is to use different prop to pass ref forward and backward:

class parent ...
    render() {
    ...
        <child inputref={this.inputref} />

class child 
...
    render() {
        <input ref={this.props.inputref} ...

it's most flexible since you may access different ref inside you child component(e.g. inputref + scrollablecontainerref + popupref)

but in some cases you want to compose new component for existing code base. say <input>'s replacement. sure, in this case you would avoid changing all <input ref={...} /> onto <myinput refprop={...}>.

here you may use react.forwardref. it feels the best with functional components like

export child = react.forwardref((props, forwardedref) => {
    ...
    return ...
        <input ref={forwardedref} />
})

but for class-based component you would rather use ref-prop with different name:

class child
...
    render()
        return
        ...
        <input ref={this.props.forwardedrefname} />

export childwithforwardref = react.forwardref((props, ref) => <child forwardedrefname={ref} {...props} />)

ps since you will consume what forwardref returns rather initial component(child) you may want to specify displayname for it. this way you may be able find it later say with enzyme's find() or easy recognize element in browser's react devtools


Related Query

More Query from same tag