Use create-react-app to create a new React application:
npx create-react-app@latest my-app
Navigate to the project directory:
cd my-app
Start the development server:
npm start
Open your browser and navigate to http://localhost:3000 to view the app.
State in a Componentsrc/App.js in your text editor.Replace the content of App.js with the following code to create a counter component:
import React, { useState } from 'react';
function App() {
// Declare a state variable 'count' and a function 'setCount' to update it
const [count, setCount] = useState(0);
// Function to increment the count
const increment = () => {
setCount(count + 1);
};
return (
<div style=>
<h1>React Counter</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default App;
count state update.Props by Creating a New Componentsrc directory named Greeting.js.In Greeting.js, define a component that accepts props:
// Greeting.js
import React from 'react';
function Greeting(props) {
return <h2>Hello, {props.name}!</h2>;
}
export default Greeting;
Modify App.js to import and use the Greeting component, passing name as a prop:
import React, { useState } from 'react';
import Greeting from './Greeting';
function App() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div style=>
<h1>React Counter with Greeting</h1>
<Greeting name="Student" />
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default App;
Modify App.js to make name dynamic, based on user input:
import React, { useState } from 'react';
import Greeting from './Greeting';
function App() {
const [name, setName] = useState('Student');
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div style=>
<h1>React Counter with Dynamic Greeting</h1>
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={(e) => setName(e.target.value)}
style=
/>
<Greeting name={name} />
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default App;
Save and check the browser. Now, you can enter a name, and the greeting will update dynamically based on the input.