top of page

React functional component written in JavaScript using JSX



import React from 'react';

const MyComponent = () => {
  const [count, setCount] = React.useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default MyComponent;

In this example, we're creating a functional component called `MyComponent`. It uses the `useState` hook from React to manage a state variable called `count`, which represents a counter. The `useState` hook returns an array with two elements: the current state value (`count`) and a function (`setCount`) to update the state.


Inside the component, we define a click event handler called `handleClick`, which increments the `count` state value by 1 when the button is clicked. The `handleClick` function is then assigned to the `onClick` event of the button.


In the JSX code within the `return` statement, we display the current value of `count` inside an `h2` heading element. Below that, we have a button with the text "Increment," and when clicked, it triggers the `handleClick` function.


Finally, the component is exported using `export default MyComponent` so it can be imported and used in other parts of your React application.


Please note that this is a simple example to demonstrate the structure of a functional component. In a real-world application, you might have more complex logic, additional state variables, and possibly other hooks or props.

Related Posts

See All

Use Props in React

To use props in React, you need to follow these steps: 1. Define a component that accepts props: Start by creating a component that...

React JS forms

Forms are really important in any website for login, signup, or whatever. It is easy to make a form in HTML but forms in React work a...

Comments


bottom of page