Properties in React

The properties in React JS is just input to a function. Why is it called as properties? To whom does the properties belong to? Explain properties in simple plain language.

Alright, let’s bring this to a level everyone can understand.

Imagine you have a robot. This robot can do lots of tasks for you. It can make coffee, it can play music, it can even clean the house! But, you need to tell this robot what to do. You need to give it some instructions or orders.

In the case of our robot, these instructions could be things like “make coffee” or “play this song”. In the context of React, these instructions are what we call “properties” or “props”.

So when you hear “properties” in React, think about it like the orders or instructions you’re giving to your robot.

Now, who does these properties belong to? They belong to the components in your React app. In our analogy, the components are like our robot.

In other words, properties are the instructions that you give to your components (robots) so they know what they should do. For instance, if you have a Button component, you might give it properties to tell it what text it should display, or what should happen when someone clicks it.

Remember, properties are just instructions you’re giving to your components. They’re how you tell your components what they should be doing.

The properties are similar to HTML attributes. In React the JSX tag can have attributes and values similar to HTML. The value of the attribute can be accessed inside the component using properties. The properties are a type of object where the value of attributes of a tag is stored. This describes the properties in a simple language. Did I miss anything?

You’re absolutely correct! That’s a great way to describe properties in React.

Just like HTML attributes, properties (props) in React define certain characteristics or values for a React component. They’re indeed passed into the component in a similar way to HTML attributes. For example, if we have a component <Button color="blue">Click me</Button>, color is a prop for the Button component.

One thing to add is that props in React are read-only. That is, a component cannot modify its own props. This maintains the “one-way data flow” principle in React, which makes it easier to track how data changes over time in the application.

So, yes, your explanation is correct and well stated! It captures the essence of how properties work in React in a clear and simple language.

What type of object is properties?

In React, the properties, or “props”, passed to a component are plain JavaScript objects.

Here’s a simple example:

1
<MyComponent someProp="Hello" />

In the component definition for MyComponent, you would access someProp from the props object like so:

1
2
3
function MyComponent(props) {
    return <h1>{props.someProp}</h1>;
}

In this case, props is an object that looks like this: { someProp: "Hello" }.

You can also destructure the props in the function arguments for a cleaner syntax:

1
2
3
function MyComponent({ someProp }) {
    return <h1>{someProp}</h1>;
}

This works the same way, but it’s a bit cleaner and more direct, especially if you’re working with multiple props.

So in essence, props in React are plain JavaScript objects where the keys are the prop names and the values are the prop values.

So the properties are like function arguments in Javascript?

Yes, that’s correct! In fact, you can think of React components as pure JavaScript functions, and props are the arguments you pass into these functions. Just as a JavaScript function can take in multiple arguments, a React component can take in multiple properties (props).

For example, if we have a JavaScript function like so:

1
2
3
function greet(name, age) {
    return `Hello, my name is ${name} and I am ${age} years old.`;
}

We can call this function with arguments like greet("Alice", 25);.

Similarly, in React, we might have a component like:

1
2
3
function Greeting(props) {
    return <h1>Hello, my name is {props.name} and I am {props.age} years old.</h1>;
}

And we can use this component with props like: <Greeting name="Alice" age={25} />.

So in both cases, we’re passing values (arguments or props) into a function (a JavaScript function or a React component), and those values are used inside the function to influence its behavior or output.

Why is it named as properties and not as arguments?

The term “properties” (or “props” in short) is borrowed from the HTML terminology. In HTML, elements have attributes that are defined by name-value pairs, like so:

1
<img src="image.jpg" alt="My Image">

Here, src and alt are attributes of the img element, and they have respective values “image.jpg” and “My Image”. These attributes essentially set “properties” of the HTML element.

In React, when we create a component, we treat it much like an HTML element. We pass in values that set the “properties” of that component, so they’re referred to as “props”. This aligns with the concept of thinking about components as encapsulated entities that have certain properties defined.

This is also because in JavaScript, the term “arguments” usually refers to the actual values that are passed to a function during invocation, whereas “parameters” refer to the variables listed as part of the function definition. However, React components receive their arguments inside a single JavaScript object. As such, they’re more similar to object properties than function arguments in the traditional sense. Therefore, the term “properties” (or “props”) is more suitable here.

The properties is passed from one pure Javascript function to another pure Javascript function to get a dynamic UI as output

Yes, that’s a good high-level description. In React, components are essentially JavaScript functions (or classes) that take inputs — called “props” — and return a React element that describes what should appear on the screen. That React element is essentially a description of the UI.

Here’s a simplified example to illustrate this. Let’s say we have a Greeting component that takes a name as a prop:

1
2
3
function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

You could use this component in another component, and pass the name prop to it:

1
2
3
function App() {
  return <Greeting name="Sara" />;
}

In this case, “Sara” is passed as a prop from the App function to the Greeting function. The Greeting function uses this prop to determine what to render — in this case, an h1 element with the text “Hello, Sara”. So yes, you’re passing props from one function to another to ultimately generate the UI.

The HTML attributes are special keywords defined in the standard whereas React element it is not?

In essence, yes. HTML attributes are predefined and have special meaning in the HTML specification. For example, the src attribute in an img tag is expected to contain a URL for the image source. The browser knows how to interpret this attribute and how to handle its value.

React elements, on the other hand, can accept any custom attributes (props) you want to define, as long as they adhere to JavaScript object syntax. This is because a React element is essentially a JavaScript object and its props are the properties of that object. Here’s an example:

1
<MyComponent customProp="Hello" anotherProp={42} />

In this case, customProp and anotherProp are not special keywords defined in any specification. They’re custom properties you defined for your MyComponent component. In your component’s code, you can access them via props.customProp and props.anotherProp.

It’s also worth noting that while you can pass any prop to a React component, when rendering HTML tags with JSX, you should use HTML attributes as defined in the HTML specification. React has a few slight differences (like className instead of class), but generally follows the HTML attribute naming.

So React component may look like a HTML tag but it is a Javascript object that has properties associated to it?

Yes, that’s a very accurate way of putting it! A React component, when defined and used in JSX, may look like an HTML tag. However, under the hood, it’s a JavaScript object (or function), and the attributes you provide in JSX are passed down as an object of properties (commonly referred to as props) to the component.

Consider the following example:

1
<MyComponent color="blue" size="large" />

In this case, MyComponent is not a typical HTML tag, it’s a custom React component. The color and size attributes are not standard HTML attributes, they’re custom properties we’ve defined. Inside the MyComponent function, you could access these via props.color and props.size.

1
2
3
function MyComponent(props) {
  return <div style={{ color: props.color, fontSize: props.size }}>Hello!</div>;
}

So while JSX may look like HTML, it’s fundamentally JavaScript, which gives us the flexibility and power to build complex UIs.

The component looks like a custom HTML tag but it is not just a static HTML tag. It encapsulates styling and user interaction?

Yes, exactly! In React, a component is a self-contained piece of code that encapsulates the markup (which might look like HTML), styles, and behavior (such as user interaction event handlers). Components can take input data, called props, and return a React element describing what should appear on the screen.

Here’s a simple example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function Button(props) {
  // define a function that will handle click events
  const handleClick = () => {
    alert('Button clicked!');
  };
  
  // return a JSX element (which looks like HTML) with styling and behavior
  return (
    <button style={{ backgroundColor: props.color }} onClick={handleClick}>
      {props.label}
    </button>
  );
}

// Usage:
// <Button color="blue" label="Click me" />

In this case, the Button component looks like a custom HTML tag but it isn’t just static HTML. It accepts properties (color and label), contains CSS styling (background color), and user interaction (a click event handler). This is a very simple example, but components can be much more complex, encapsulating significant portions of your app’s UI, state, and logic.

Instead of building a dynamic UI using HTML file, CSS file and Javascript files stored as 3 separate files, React combines all three files into one .js or .jsx file to create a dynamic UI element?

Yes, that’s correct! React indeed allows you to combine HTML-like syntax (JSX), CSS, and JavaScript into a single .js or .jsx file to define a component. This approach has several benefits:

  1. Encapsulation: Each component is self-contained, meaning that the markup, logic, and styles for a component are all defined in one place. This can make your code easier to understand and maintain, because you don’t have to look in multiple files to understand what a component does.

  2. Reuse and Composition: Components are reusable and can be combined to create complex user interfaces. For example, you might have a Button component that you use in several different places in your app. If you want to change how all your buttons look or behave, you only need to change the code in one place (the Button component), and the changes will be applied everywhere that component is used.

  3. Modularity: With React’s component-based architecture, each piece of your user interface is modular. This means that components can be developed and tested independently, which can be a big productivity boost especially in large projects with multiple developers.

Remember that while it is common to include styles within components in React, especially when using CSS-in-JS solutions like styled-components or Emotion, it’s not strictly required. It’s also perfectly valid to keep your CSS in separate files and use traditional CSS classes if that better suits your project’s needs.

It makes it easier to understand code because in large code bases you have to scroll up and down to find relevant sections in the code for a given section of the UI.

Exactly!

React’s component-based structure encourages the organization of code into self-contained modules, which represent a distinct part of the UI. This structure often leads to more maintainable and understandable code bases, especially for large applications.

Instead of having to search through a large HTML file to find the relevant code for a specific part of your UI, you can simply go to the specific React component that represents that part of the UI. Similarly, any JavaScript functions or CSS styles that are specific to that part of the UI can be defined within or near that component, reducing the need to scroll through large JS or CSS files.

In addition to making it easier to find relevant code, this structure also makes it easier to reason about your application’s behavior. Because each component is self-contained, you can often understand the behavior of a part of your UI by looking at a single component, rather than having to understand the entire codebase. This modularity is one of the reasons why React (and similar component-based frameworks) are popular for developing large web applications.

The old way of building things separated the HTML, CSS and Javascript. What is the reason behind the separation of concerns in the old way of building web UI?

The separation of concerns in the traditional web development model (HTML, CSS, JavaScript) is primarily for clarity and maintainability.

  1. HTML: It’s the structure of your webpage. It’s where you lay out your content in a semantic, meaningful way.

  2. CSS: It’s the presentation layer. It’s used to style your webpage – colors, layouts, fonts, etc. It helps to make the webpage aesthetically pleasing and provides a better user experience.

  3. JavaScript: It’s the behavior layer. It makes your webpage interactive, handling user events, performing calculations, and modifying the HTML and CSS on the fly.

The main idea was that by separating these aspects of a webpage, a developer could work on one aspect without worrying too much about the others. For example, a change to the CSS would (ideally) not break the JavaScript.

However, with the rise of modern JavaScript frameworks like React, this separation of concerns shifted from a technology-based separation (HTML, CSS, JavaScript) to a component-based separation. Each component encapsulates its own structure (HTML), presentation (CSS), and behavior (JavaScript). This approach has been found to be more efficient and maintainable for building complex, large-scale applications.

It’s also worth noting that even with React or similar frameworks, you can still separate HTML, CSS, and JavaScript in different files if that suits your project’s needs. For example, you might use CSS modules or similar approaches to put your CSS in separate files, but still have each component’s CSS be specifically tied to that component.

The separation of concerns is still a valid and useful principle. It’s just that the definition of a “concern” has evolved with these new tools and methodologies.

What was the old definition of concern? What is the new definition of concern?

The concept of “separation of concerns” has its roots in computer science and software engineering, and it’s all about making software more understandable, maintainable, and modular.

In the older context, particularly in web development, a “concern” was typically considered a distinct area of functionality or technology. This was often split along the lines of the core web technologies:

  • HTML was the concern for defining the structure of web content.
  • CSS was the concern for presenting the content in a visually appealing way.
  • JavaScript was the concern for adding dynamic behaviors, interactivity, and more complex logic to the webpage.

These concerns were primarily technology-based. Each one had its specific role and they were intended to work together, yet be maintained separately for clarity and simplicity.

However, with the rise of modern JavaScript frameworks and libraries like React, Angular, and Vue, the concept of a “concern” has shifted to be more feature- or component-centric:

  • Now, a “concern” might be a distinct part of your application’s functionality, encapsulated in a component or a group of related components.
  • For example, a navigation bar might be a concern, with its own HTML (structure), CSS (presentation), and JavaScript (behavior) grouped together.

This shift provides a number of advantages, especially in larger, more complex applications. By encapsulating related structure, presentation, and behavior together, these modern approaches make it easier to understand, update, and reuse parts of your application. This also aligns more closely with the way many teams are structured, where cross-functional teams are responsible for distinct features or areas of an application.

It’s important to note, however, that the core idea behind separation of concerns hasn’t changed: It’s still about breaking down software into distinct, manageable pieces to make it easier to understand, maintain, and develop. The specifics of what constitutes a “concern” have simply evolved along with the tools and methodologies we use.