Dynamically Create Ref in Constructor

dynamic refs react
react createref
react ref is null
what are refs
react.createref is not a function
react array of refs
textarea ref
html ref

I want to make my child components have a ref, but I don't want the user to have to specify the ref when they create the component. So say I have something like this:

<Parent>
    <Child />
    <Child />
</Parent>

And I want the parent to be able to access the Child components' state. The easy way is to add a ref to each component, but I would like this to the be something that is done during the constructor() function to abstract this away from the end user, as I'd like these components to be generalized.

Is there a clean way to make it so the parent can access the state of the child components, such as when the Child is created you have something like:

class Child extends Component {
    constructor(){
        super();
        this.state = {'abc': 123}
        this.ref=Math.random();
    }
}

So that inside of the Parent class I can do something like:

 class Parent extends Component {
     componentWillMount(){
         console.log(this.refs);
     }
 }

So I want to be able to declare a set of components like:

class App extends Component {
    render(){
       <Parent> <Child /> <Child /> </Parent>
    }
}

So that I can access each child and it's state as the parent iterates through child components.

  1. I want the parent to be able to access the Child components' state.

State is only accessible to component itself. Parent and child component can access only their own state. You can pass value to child state as props but parent can't access child component state itself.

  1. Setting Refs to child component.

    Why do you want this? Ref is for Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries.

    Please visit this link to understand the uses of Ref. https://facebook.github.io/react/docs/refs-and-the-dom.html

Anyway, components can have their own refs, and you can set ref to child components,

render: function() {
    return (
      <div>
        <Child ref="child" />
        <div><button onClick={this.handleClick}>ACCESS REF</button></div>
      </div>
    );
  },

handleClick: function() {
    alert(this.refs.child.refs.input.getDOMNode().value);
  }
});

let Child = React.createClass({
  render: function() {
    return <input ref="input" />;
  }
});

I will suggest , you should either pass callbacks into children as props to do your stuff.:

React Refs with Dynamic Names - Julien Mayer, If you want to create a ref to use in react but don't know what the name will be ahead of time You can access the correct this inside of a loop in the constructor​. Dynamically invoking a constructor with Reflection in .NET C#. Say you do not have access to a .NET assembly at compile time but you want to run code in it. It’s possible to dynamically load an assembly and run code in it without early access. Here we’ll see how to invoke a constructor of a type in a referenced assembly.

I needed this exact same thing for a form I was making and this is what I came up with to add the refs to the child components automatically

Given that you have:

<Parent>
    <Child />
    <Child />
</Parent>

You can use this in the Parent component render function to add a ref to every child.

render () {
  let wrappedChildren = [];

  React.Children.map(this.props.children, (child, i)=> {
    if (!child) {
      return;
    }
      let refName = 'child' + i
      wrappedChildren.push(React.cloneElement(child, {
        key: refName,
        ref: refName,
      }
    ));
  }, this);
  return (
    <View>
        {wrappedChildren}
    </View>
  )
}

This will add a ref to every Child consisting of a string plus the index of the current map and then render them in the same order, giving you the equivalent of doing this:

<Parent>
    <Child ref="child0" />
    <Child ref="child1" />
</Parent>

I know that string refs are deprecated but i was trying to keep it simple you can also use refs as callbacks by changing:

ref: refName

to:

ref: (c) => { this[refName] = c }

And then used it in the parent component as this.child0 for example.

Hope it helps.

The Complete Guide to React Refs, In order to simplify things, the createRef API came into play. Consider then the common case when you want to programmatically trigger focus on an element: or by binding the callback to a class method in the constructor. When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

In this approach the Parent component is the one where the children are being used in render. You can manipulate the childrens' "state" by calling a method of them.

Parent.js

class Parent extends Component {
  refs = [];

  componentDidMount() {
    this.refs[0].doSelect();
  }

  setRef = ref => {
    this.refs.push(ref);
  }

  render() {
    return (
      <div>
        <Child ref={this.setRef} />
        <Child ref={this.setRef} />
      </div>
     )
   }
}

Child.js

class Child extends Component {
  state = { isSelected: false }

  doSelect = () => {
    this.setState({ isSelected: true })
  }

  render() {
    return <div className="child" />
  }
}

How to use React createRef, Refs provide a way to access DOM nodes or React elements created in the render First, in the constructor() , we created a ref using React. The next project that you create in this walkthrough accesses a library that is written in the dynamic language IronPython. To create a custom dynamic class. In Visual Studio, on the File menu, point to New and then click Project. In the New Project dialog box, in the Project Types pane, make sure that Windows is selected.

React `ref` doesn't work with dynamically imported components , creating a callback reference to a dynamically imported component, default class extends Component { constructor(props) { super(props)  Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class. The following example shows a class TextEditor that can only be dependency-injected with constructor injection. Let us have a working Eclipse IDE in place and take the following steps

Dynamic Components with Content Projection in Angular « ng-book , In this example, we'll show how to create a dynamically generated export class NavComponent { constructor(private modal: ModalService) A componentRef exposes a reference to the native DOM element which we append to the body. A constructor of a structure type must initialize all instance fields of the type. A structure type can't inherit from other class or structure type and it can't be the base of a class. However, a structure type can implement interfaces .

Use Array.map() to Dynamically Render Elements - JavaScript, Component { constructor(props) { super(props); // change code below this line handleSubmit}>Create List</button> <h1>My "To Do" List:</h1> <ul> {items} </ul​> {$$typeof: Symbol(react.element), type: “p”, key: null, ref: null, props: {…}, …} 1) Using new Keyword : Using new keyword is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors). // Java program to illustrate creation of Object.

Comments
  • You can not access child component state from parent. State can be accessed, modified from it own class.
  • you actually can with a ref
  • I mean setting state of child component state from parent. You cant do this
  • check this. stackoverflow.com/questions/27864951/…
  • so you can't add a ref during the constructor?
  • you are totally going wrong way. First go through answer and link posted.
  • ehh, it's a weird use case, I'm repurposing React components for something outside of web dev so it might not be awful
  • how would you set the ref on create?
  • <Child ref="child" />