Reactjs - Object Oriented?

I am starting to use Reactjs and, based on OO (Java), I was curious if we could use React in a true object-oriented style with true inheritance and composition.

USING CASE: We create React components in the library for reuse by our developers. Can we do this in an object oriented way? For example, can I have a common input text field with some basic styles / behavior and then have another MyInput field that extends the input that the properties and behavior from Input can use?

It seems that most of what I learned React uses states and reducers in the application itself to control everything; which seems to me that he lacks the meaning of OO design. But maybe I'm wrong. Any information would be most helpful.

+8
javascript oop reactjs
source share
2 answers

First of all, I would like to tell you that React is based on Javascript , which is obviously object oriented (but not quite similar to languages ​​like Java, C ++, and many other traditional object oriented languages).

The reaction itself does not apply an object-oriented technique, but the Response components are completely reused. You can create common components from a very simple text input field, shortcuts to complex and reusable.

If you come from the JAVA world, then I would suggest you use Javascript es6 to get a little involved in the class.

Sample React Component in Javascript es6

class Text extends React.Component { render() { return <p>{this.props.children}</p>; } } React.render(<Text>Hello World</Text>, document.body); 

See how inheritance works

 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } } class CPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } toString() { return super.toString() + ' in ' + this.color; } } 

All the code you see is in Javascript!

For React, you can split your application into Presentation Components and Container Components for better reuse and structuring.

  • Presentation components: mainly related to the reception of data through the details and their display. They do not determine how data is loaded or mutated and do not have their own states.

Example

 const Text = ({ children = 'Hello World!' }) => <p>{children}</p> 
  • Container components: transfers data and behavior to presentation or other container components. They have their own states. You can generate data here and pass it on to representative components.

Example

 class Contacts extends React.Component { constructor(props) { super(props); this.state = { message:"new message" }; } render() { return ( <div><Text children={this.state.message}/></div> ); } } 

I suggest staying away from Mixins. Mixins arent support in ES6 classes.

+6
source share

You can create mixins to exchange functions between components. Inheritance strengthens the rigid connection of components, and ultimately it can be consistent.

+2
source share

All Articles