DEV Community

von CARAMEL
von CARAMEL

Posted on

React Introduction

Creating a Component
function Greeting() {
return

Hello World

;
}

export default Greeting;
Using a Component
import Greeting from './Greeting';

function App() {
return (




);
}

export default App;
Props

Props allow you to pass data from one component to another.

function Greeting(props) {
return

Hello {props.name}

;
}

Usage:

Output:

Hello John
useState

useState lets you store and update data inside a component.

import { useState } from 'react';

function Counter() {

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

return (
<>

{count}

  <button
    onClick={() => setCount(count + 1)}
  >
    +
  </button>
</>
Enter fullscreen mode Exit fullscreen mode

);
}
useEffect

useEffect runs code when the component loads or when dependencies change.

import { useEffect } from 'react';

useEffect(() => {
console.log("Component loaded");
}, []);

The empty array:

[]

means:

Run only once when the component is mounted.

Conditional Rendering
function User({ loggedIn }) {

return (

<>

{loggedIn

?

Welcome



:

Please log in



}

</>

);

}

Rendering Lists

const users = [

"Alice",

"Bob",

"John"

];

return (

    {users.map((user, index) => (
  • {user}
  • ))}


);

Top comments (0)