Skip to content

[Feature]: Add Output in React.Js Course in Docs section #3957

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,31 @@ const DataFetcher = () => {
export default DataFetcher;
```

<BrowserWindow>
<div>
<h2>Fetched Data</h2>
<p id="load_ing" style={{fontFamily:"monospace",textAlign:'center',fontWeight:"600",fontSize:"1.2rem"}}>Fetching....</p>
<ul id="u_l"></ul>
<script>
document.addEventListener("DOMContentLoaded", (event) => {
setTimeout(()=>{
if(document.getElementById("load_ing")?.style){document.getElementById("load_ing").style.display="none";}
[{id:1,name:"John"},{id:2,name:"sam"},{id:3,name:"Arjun"},{id:4,name:"siva"},{id:5,name:"Anbhu"},{id:6,name:"Krishna"}].map(item=>{
let li=document.createElement("li")
li.textContent=item.name
let ul=document.getElementById("u_l")
if(ul){
ul.appendChild(li)
}
})
},1500)
})
</script>
</div>
</BrowserWindow>



In this component, we use the `useEffect` hook to fetch data from the API when the component mounts. We store the fetched data in the `data` state variable using the `useState` hook.

### Step 4: Using the DataFetcher Component
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,29 @@ const App = () => {
export default App;
```

<BrowserWindow>
<div>
<h2>My React App</h2>
<p id="loa_d_ing" style={{fontFamily:"monospace",textAlign:'center',fontWeight:"600",fontSize:"1.2rem"}}>Fetching....</p>
<ul id="u_l_"></ul>
<script>
document.addEventListener("DOMContentLoaded", (event) => {
setTimeout(()=>{
if(document.getElementById("loa_d_ing")?.style){document.getElementById("loa_d_ing").style.display="none";}
[{id:1,name:"Leet Code Solutions"},{id:2,name:"Responsive Missing"},{id:3,name:"Amazing work projects"},{id:4,name:"Blogs news"},{id:5,name:"130+ contributors"},{id:6,name:"Our Team Members"}].map(item=>{
let li=document.createElement("li")
li.textContent=item.name
let ul=document.getElementById("u_l_")
if(ul){
ul.appendChild(li)
}
})
},2500)
})
</script>
</div>
</BrowserWindow>

In this code, we use the `useState` and `useEffect` hooks from React to manage the state of the `posts` array. The `useEffect` hook makes an HTTP GET request to `/api/posts` when the component mounts. The response data is then used to update the `posts` state, and the list of posts is displayed in the app.

### Sending Data to the Backend
Expand Down Expand Up @@ -134,7 +157,7 @@ const App = () => {
</form>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
<li key={post.id}><span>{post.title}</span><span>{post.body}</span></li>
))}
</ul>
</div>
Expand All @@ -144,6 +167,36 @@ const App = () => {
export default App;
```

<BrowserWindow>
<div>
<h2>My React App</h2>
<form style={{display:"flex",flexDirection:"column",gap:"0.4rem"}} onSubmit={(event)=>{
event.preventDefault();
let dispaly_data=document.getElementById("dispaly_data")
let li=document.createElement("li")
li.style.display="flex"
li.style.flexDirection="column"
li.style.border="0.1rem solid"
li.style.margin="0.5rem"
li.style.padding="0.5rem"
let span1=document.createElement("span")
let span2=document.createElement("span")
span1.textContent=`Title: ${event.target.title.value}`
span2.textContent=`body: ${event.target.body.value}`
li.appendChild(span1)
li.appendChild(span2)
dispaly_data.appendChild(li)
}}>
<input type="text" name="title" placeholder="Enter title" required style={{padding:"0.5rem 2rem 0.5rem 0.5rem"}}/>
<textarea name="body" placeholder="Enter body" required style={{padding:"0.5rem 2rem 0.5rem 0.5rem"}}/>
<button type="submit" style={{padding:"0.8rem",width:"200px",background:"rgb(0,123,255)",border:"none",borderRadius:"0.5rem",color:"white"}}>Create Post</button>
</form>
<ul id="dispaly_data">
<li style={{display:"flex",flexDirection:"column",border:"0.1rem solid",margin:"0.5rem",padding:"0.5rem"}}><span>Title: Sample Post</span><span>body: Hello Users, This is sample post create you own post</span></li>
</ul>
</div>
</BrowserWindow>

In this code, we added a form with inputs for the title and body of the post. When the form is submitted, the `handleSubmit` function is called, which captures the values of the form fields and sends a POST request to `/api/posts`. If the request is successful, the new post is added to the `posts` state, and the list is updated automatically.

## Conclusion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,30 @@ function App() {
export default App;
```

<BrowserWindow>
<div>
<h1>Welcome to My React app</h1>
<p id="loading" style={{fontFamily:"monospace",textAlign:'center',fontWeight:"600",fontSize:"1.2rem"}}>Fetching....</p>
<ul id="ul"></ul>
<script>
document.addEventListener("DOMContentLoaded", (event) => {
setTimeout(()=>{
if(document.getElementById("loading")?.style){document.getElementById("loading").style.display="none";}
[{id:1,name:"John"},{id:2,name:"sam"},{id:3,name:"Arjun"},{id:4,name:"siva"},{id:5,name:"Anbhu"},{id:6,name:"Krishna"}].map(item=>{
let li=document.createElement("li")
li.textContent=item.name
let ul=document.getElementById("ul")
if(ul){
ul.appendChild(li)
}
})
},2500)
})
</script>
</div>
</BrowserWindow>


## "Invalid Host Header" Error and How to Handle It

In some cases, after configuring the proxy, you might encounter an "Invalid Host Header" error when developing remotely. This issue arises due to stricter host checks to prevent DNS rebinding attacks.
Expand Down
61 changes: 61 additions & 0 deletions docs/react/getting-started/forms-in-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);
```

<BrowserWindow>
<form>
<label htmlFor="name">Enter your name: </label>
<input type="text" id="name" />
</form>
</BrowserWindow>

This will work as normal, the form will submit and the page will refresh.

But this is generally not what we want to happen in React.
Expand Down Expand Up @@ -68,6 +75,13 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);
```

<BrowserWindow>
<form>
<label htmlFor="name">Enter your name: </label>
<input type="text" id="name" />
</form>
</BrowserWindow>

## Forms

These docs are old and won’t be updated. Go to react.dev for the new React docs.
Expand Down Expand Up @@ -133,6 +147,19 @@ class NameForm extends React.Component {
}
```

<BrowserWindow>
<form onSubmit={(event)=>{
event.preventDefault();
let name = event.target.elements.name.value;
alert(`A name was submitted: ${name}`);
}}>
<label >Name: </label>
<input type="text" id="name" required />
<br />
<input type="submit" />
</form>
</BrowserWindow>

Since the `value` attribute is set on our form element, the displayed value will always be `this.state.value`, making the React state the source of truth. Since `handleChange` runs on every keystroke to update the React state, the displayed value will update as the user types.

With a controlled component, the input’s value is always driven by the React state. While this means you have to type a bit more code, you can now pass the value to other UI elements too or reset it from other event handlers.
Expand Down Expand Up @@ -183,6 +210,20 @@ class EssayForm extends React.Component {
}
}
```
<BrowserWindow>
<form onSubmit={(event)=>{
event.preventDefault();
let name = event.target.elements.name.value;
alert(`An essay was submitted: ${name}`);
}}>
<div style={{display:"flex",justifyContent:"flex-start",gap:"0.5rem",alignItems:"center"}}>
<label >Essay: </label>
<textarea type="text" id="name" required />
</div>
<br />
<input type="submit" />
</form>
</BrowserWindow>

Notice that `this.state.value` is initialized in the constructor so that the text area starts off with some text in it.

Expand Down Expand Up @@ -239,6 +280,26 @@ class FlavorForm extends React.Component {
}
```

<BrowserWindow>
<form onSubmit={(event)=>{
event.preventDefault();
let name = event.target.elements.name.value;
alert(`Your favorite flavor is: ${name}`);
}}>
<div style={{display:"flex",justifyContent:"flex-start",gap:"0.5rem",alignItems:"center"}}>
<label > Pick your favorite flavor: </label>
<select id="name" >
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</div>
<br />
<input type="submit" />
</form>
</BrowserWindow>

Overall, this makes it so that `<input type="text">`, `<textarea>`, and `<select>` all work very similarly - they all accept a `value` attribute that you can use to implement a controlled component.

### Handling Multiple Inputs
Expand Down
10 changes: 10 additions & 0 deletions docs/react/hooks/useCallback.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,14 @@ function MemoizedCounter() {
}
```

<BrowserWindow>
<div>
<p>You clicked <span id="display">0</span> times</p>
<button onClick={()=>{
let display=document.getElementById("display")
display.textContent=Number(display.textContent)+1
}}>Click me</button>
</div>
</BrowserWindow>

In this example, `useCallback` memoizes the `increment` function to ensure that it only changes when `count` changes. This optimization prevents unnecessary re-renders of `MemoizedCounter` when passed as a prop to child components.
6 changes: 6 additions & 0 deletions docs/react/hooks/useContext.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,10 @@ function ThemeComponent() {
}
```

<BrowserWindow>
<div>
<p>Current theme:<span id="Theme">light</span></p>
</div>
</BrowserWindow>

In this example, `ThemeComponent` uses `useContext` to consume the current theme value (`'light'`) provided by the nearest `ThemeContext.Provider` higher up in the component tree.
18 changes: 18 additions & 0 deletions docs/react/hooks/useEffect-hook.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,23 @@ function Timer() {
);
}
```
<BrowserWindow>
<div>
<p>Timer: <span id="Timer" >0</span></p>
<script>
document.addEventListener("DOMContentLoaded", () => {
setInterval(() => {
if(document.getElementById("Timer")){
document.getElementById("Timer").textContent = Number(document.getElementById("Timer").textContent)+1
}
else{
return
}
}, 1000)
})
</script>
</div>
</BrowserWindow>


In this example, `useEffect` is used to create a timer that updates the `seconds` state every second (`1000ms`). The cleanup function returned by `useEffect` clears the interval when the component unmounts or when `seconds` changes due to a dependency array (`[]`) change.
27 changes: 22 additions & 5 deletions docs/react/hooks/useMemo.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ sidebar_position: 6
tags: [react, create-react-app, useMemo, hooks, react-scripts, react-dom, react-app]
---

### useMemo

**Explanation:**
`useMemo` is used to memoize expensive calculations or computations so that they are only recomputed when necessary. It is similar to `useCallback`, but instead of memoizing functions, it memoizes the result of a computation.

When you call `useMemo`, you pass it a function that performs the expensive computation and a dependency array. It returns the memoized value that only changes when one of the dependencies has changed.
Expand All @@ -31,12 +28,32 @@ function MemoizedFactorial() {

return (
<div>
<span>Enter a number to calculate its factorial: </span>
<input type="number" value={number} onChange={(e) => setNumber(Number(e.target.value))} />
<p>Factorial of {number} is: {factorial}</p>
{/* Input updates 'number' to recompute factorial */}
<input type="number" value={number} onChange={(e) => setNumber(Number(e.target.value))} />
</div>
);
}
```

<BrowserWindow>
<div>
<span>Enter a number to calculate its factorial: </span>
<input type="number" onChange={(e) => {
let number=Number(e.target.value)
let give_num=document.getElementById("give_num")
let output_num=document.getElementById("output_num")
let fact = 1;
for (let i = 1; i <= number; i++) {
fact *= i;
}
give_num.textContent=number
output_num.textContent=fact
}} />
<br />
<br />
<p>Factorial of <span id="give_num"> </span> is: <span id="output_num"> </span></p>
</div>
</BrowserWindow>

In this example, `useMemo` memoizes the `factorial` calculation based on the `number` state. It ensures that the factorial computation is only recalculated when `number` changes, optimizing performance by avoiding unnecessary computations on each render.
10 changes: 10 additions & 0 deletions docs/react/hooks/useReducer.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,14 @@ function Counter() {
}
```

<BrowserWindow>
<p>Count: <span id="countValue">0</span></p>
<button onClick={() =>{
document.getElementById("countValue").textContent=Number(document.getElementById("countValue").textContent)+1
}}>Increment</button> &nbsp;
<button onClick={() => {
document.getElementById("countValue").textContent=Number(document.getElementById("countValue").textContent)-1
}}>Decrement</button>
</BrowserWindow>

In this example, `useReducer` manages state updates for `count`. `dispatch` is used to trigger actions (`{ type: 'increment' }` or `{ type: 'decrement' }`), which are processed by the `reducer` function to compute the next state.
8 changes: 7 additions & 1 deletion docs/react/hooks/useState-hook.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,11 @@ function Counter() {
);
}
```
<BrowserWindow>
<div>
<p>You clicked <span id="displayCount">0</span> times</p>
<button onClick={()=>{document.getElementById("displayCount").textContent=Number(document.getElementById("displayCount").textContent)+1}}>Click me</button>
</div>
</BrowserWindow>

In this example, `count` is the state variable initialized to 0, and `setCount` is the function used to update `count`. When the button is clicked, `setCount` is called with the new value of `count + 1`, causing the component to rerender with the updated count displayed.
In this example, `count` is the state variable initialized to 0, and `setCount` is the function used to update `count`. When the button is clicked, `setCount` is called with the new value of `count + 1`, causing the component to rerender with the updated count displayed.
Loading