DEV Community

Cover image for What is ReactJs?
Muhib ur Rahman Bakar
Muhib ur Rahman Bakar

Posted on

What is ReactJs?

React is a JavaScriptlibrary for building user interfaces. It allows you to build reusable UI components and manage the state of your application efficiently. Here's a beginner's tutorial for ReactJS using examples:

Setting up a React environment:
To start building with React, you need to set up a development environment. You can do this using tools like CodeSandboxor you can set up a local environment using npm and a text editor like Visual Studio Code.

Creating a React component:
A componentin React is a piece of UI that can be reused multiple times in an application. You can create a component in React using JavaScript functionsor classes. Here's an example of a functional component:

import React from "react";

function MyComponent() {
  return <h1>Hello, World!</h1>;
}

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

And here's an example of a class component:

import React, { Component } from "react";

class MyComponent extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

Rendering a component:
To render a component in React, you need to import it into a file and use the <MyComponent /> syntax to render it. Here's an example:

import React from "react";
import MyComponent from "./MyComponent";

function App() {
  return (
    <div>
      <MyComponent />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Props and State:
In React, you can pass data to components using props and manage the state of a component using the state object. Props are properties that are passed to a component from its parent component. The state is an object that holds data that can change within a component. Here's an example:

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Event handling:
You can handle events in React components using event handlers. An event handler is a function that is executed when an event occurs, such as a button click. Here's an example:

import React, { useState } from "react";

function Toggler() {
  const [isToggled, setToggled] = useState(false);

  return (
    <div>
      <p>Toggled: {isToggled.toString()}</p>
      <button onClick={() => setToggled(!isToggled)}>Toggle</button>
    </div>
  );
}

export default Toggler;
Enter fullscreen mode Exit fullscreen mode

These are the basics of ReactJS. Visit React Docs for more. You can use these concepts to build more complex applications and learn advanced topics as you progress.
Follow @bakardev for more. ✌

Top comments (0)