Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs - Get a component from anywhere in the app

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...

like image 924
edu Avatar asked Nov 13 '13 14:11

edu


People also ask

How do you find where a component is used in React?

There's two ways to find: React Developer Tools extension (recommended) tool for debugging. It has a Search bar (text or/regex/)

How do you access context outside of component?

To access a React context outside of the render function, we can use the useContext hook. We create the UserContext by calling the React. createContext method with a default context value. Then in the Users component, we call the useContext hook with UserContext to accxess the current value of UserContext .

How do I create a global component in ReactJS?

Hmm, there isn't any kind of "global" component in React. Each component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though: 1) Create a Higher Order Component that renders the PageContent and the wrapped component.


1 Answers

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.

like image 128
Paul O'Shannessy Avatar answered Sep 29 '22 19:09

Paul O'Shannessy