0

I would like to know:

  • How to create react components dynamically, for example from some simple objects.
  • Can the dynamic creation works also in JSX?

  • Does react offer a way to retrieve a component after has been created? For example by its id others meanings?

If you could provide me a minimalist working example I really appreciate it thanks!

    var data = [{
      type: 'button',
      props: {
        className: 'button button-blue',
        children: {
          type: 'b',
          props: {
            children: 'OK!'
          }
        }
      }
    },{
      type: 'button',
      props: {
        className: 'button button-blue',
        children: {
          type: 'b',
          props: {
            children: 'OK!'
          }
        }
      }
    }
];
2
  • why a downvote? please add a comment so I can improve my question Commented May 15, 2017 at 12:57
  • It wasn't from me, but I am guessing it's because you're asking for someone to write code for you, without explaining the intended use. Commented May 15, 2017 at 13:28

1 Answer 1

1

You've made a nice list of things you don't do with React. The whole point of React is to declare how your component tree depends on the data and let the framework manage it for you. There's very few exceptional cases when you may want to do something hacky, though.

How to create react components dynamically, for example from some simple objects.

Can the dynamic creation works also in JSX?

You use React.createElement(). You have to use it once to initialize the framework. Other use cases I could think of is injecting things like modals into or rendering into DOM generated by non-React library or component wrapped in a React component (basically a way to give control back to React). Unless you are doing one of those thing or really really know what you're trying to achieve, try to avoid this. For example, if you need a component that is sometimes rendered and sometimes not, use conditional rendering in your JSX, like this:

render() {
    return (
        <Something>
            <SomethingElse />
            {this.props.someProp ? <SomethingConditional /> : null}
        </Something>
    );
}

Does react offer a way to retrieve a component after has been created? For example by its id others meanings?

https://facebook.github.io/react/docs/refs-and-the-dom.html

Again, try to use this only to inspect the DOM or do things that would be impossible or wasteful otherwise, like focus. Do not use it to modify DOM.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.