0

I'm very new to React and I'm trying to make a simple application that renders html controls.

I want to have an API that return array of json objects contains properties that determine the type and the value of each control like id, type, value ... etc.

Let's say that I have some controls like Input and Button.

What I'm thinking of is Creating a base class named HtmlControl that extends React.Component and other html controls should extend from the HtmlControl and finally a class for rendering these controls.

How can I be able to render the controls that extends only HtmlControl class ?

1 Answer 1

1

That would not be a good choice as react says you should not focus inheritance rather focus on containment or composition.

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components.

and

At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.

Props and composition give you all the flexibility you need to customize a component's look and behavior in an explicit and safe way. Remember that components may accept arbitrary props, including primitive values, React elements, or functions.

Please Visit this link to learn more.

You can create separate classes for each of the components or elements and combine them in one class like this:

import Button from './Button'
import Radio from './Radio'
import TextInput from './TextInput'

class HtmlComponent{
 // note: we don't need to extend it from React.Component
 // we will some function to render them.

 renderTextInput()  { <TextInput /> }
 renderRadio()  { <Radio /> }
}

// you can now use below code:
const hC = new HtmlComponent();
hC.renderTextInput();

Note Again this is not a nice idea to do but you can achieve your goal.

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

1 Comment

So, what's your opinion to apply this idea ?

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.