7

I'd like to know if there is a way to get a component by using some type of id, or by type, similar as you would do in DOM manipulation. Something like:

var Avatar = React.createClass({
    render: function () {
        ...
    }
});
React.renderComponent(Avatar({id:'avatar'}), ...);
...
...
var avatar = React.getComponentById('avatar');
avatar.setProps({url = 'http://...'});
// or
var avatars = React.getComponentByType('Avatar'); 
if (avatars.length) {
    avatars[0].setProps({url = 'http://...'});
}

I don't want to keep references of components instances...

hungerstar
  • 21,206
  • 6
  • 50
  • 59
edu
  • 73
  • 1
  • 5

2 Answers2

8

setProps is something that you should use sparingly. In fact storing references to "rendered" components in general might indicate that you can structure your code differently. We also limit your uses of setProps to top level components.

var avatar = React.renderComponent(<Avatar .../>, node);
avatar.setProps({ foo: '1' });

is equivalent to this, which fits in a bit better with the declarative model:

React.renderComponent(<Avatar .../>, node);
React.renderComponent(<Avatar ... foo="1" />, node);

You could wrap that render up inside a function call so you could call it at will.

Paul O'Shannessy
  • 2,498
  • 17
  • 10
  • It would be awesome to have some nontrivial open-source examples of how to structure a reactjs app :) @Paul – Jared Forsyth Dec 07 '13 at 21:24
  • 1
    Have you read this link? Its a bit above trivial, but not so complicated as to be difficult to understand for a new dev to react: http://facebook.github.io/react/blog/2013/11/05/thinking-in-react.html – Edward M Smith Jan 22 '14 at 21:02
3

Sorry, there's no (publicly exposed) global registry of mounted React components. If you need to send messages to a component after mounting it, the best way is to save a reference to it. Iterating through the list of all Avatar components seems like the wrong solution to me anyway because it wrecks the composability aspect of components, where each parent component can specify its child's props and trust that outside forces won't change them -- changing this makes your page harder to reason about.

If you provide a jsfiddle of what you're trying to do, perhaps I can be of more help.

Sophie Alpert
  • 139,698
  • 36
  • 220
  • 238
  • Thanks for the answer. I'm just trying to figure out how to structure apps in Reactjs. I'll post more about this later on... – edu Nov 15 '13 at 09:49