diff --git "a/react_retrieval.json" "b/react_retrieval.json"
deleted file mode 100644--- "a/react_retrieval.json"
+++ /dev/null
@@ -1,600 +0,0 @@
-[
- {
- "id": "bd9e83073a0a",
- "url": "https://react.dev/learn",
- "title": "Quick Start – React",
- "content": "Learn React Quick Start Welcome to the React documentation! This page will give you an introduction to 80% of the React concepts that you will use on a daily basis. You will learn How to create and nest components How to add markup and styles How to display data How to render conditions and lists How to respond to events and update the screen How to share data between components Creating and nesting components React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page. React components are JavaScript functions that return markup: \n\n```\nfunction MyButton() { return ( );}\n```\n\n Now that you’ve declared \n\n```\nMyButton\n```\n\n, you can nest it into another component: \n\n```\nexport default function MyApp() { return (
Welcome to my app
);}\n```\n\n Notice that \n\n```\n\n```\n\n starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase. Have a look at the result: App. js App. js Reload Clear Fork \n\n```\nfunction MyButton() {\n return (\n \n );\n}\nexport default function MyApp() {\n return (\n
\n
Welcome to my app
\n \n
\n );\n}\n```\n\n Show more The \n\n```\nexport default\n```\n\n keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, MDN and javascript. info have great references. Writing markup with JSX The markup syntax you’ve seen above is called JSX. It is optional, but most React projects use JSX for its convenience. All of the tools we recommend for local development support JSX out of the box. JSX is stricter than HTML. You have to close tags like \n\n```\n \n```\n\n. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a \n\n```\n
...
\n```\n\n or an empty \n\n```\n<>...>\n```\n\n wrapper: \n\n```\nfunction AboutPage() { return ( <>
About
Hello there. How do you do?
> );}\n```\n\n If you have a lot of HTML to port to JSX, you can use an online converter. Adding styles In React, you specify a CSS class with \n\n```\nclassName\n```\n\n. It works the same way as the HTML \n\n```\nclass\n```\n\n attribute: \n\n```\n\n```\n\n Then you write the CSS rules for it in a separate CSS file: \n\n```\n/* In your CSS */.avatar { border-radius: 50%;}\n```\n\n React does not prescribe how you add CSS files. In the simplest case, you’ll add a \n\n```\n\n```\n\n tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project. Displaying data JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display \n\n```\nuser.name\n```\n\n: \n\n```\nreturn (
{user.name}
);\n```\n\n You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, \n\n```\nclassName=\"avatar\"\n```\n\n passes the \n\n```\n\"avatar\"\n```\n\n string as the CSS class, but \n\n```\nsrc={user.imageUrl}\n```\n\n reads the JavaScript \n\n```\nuser.imageUrl\n```\n\n variable value, and then passes that value as the \n\n```\nsrc\n```\n\n attribute: \n\n```\nreturn ( );\n```\n\n You can put more complex expressions inside the JSX curly braces too, for example, string concatenation: App. js App. js Reload Clear Fork \n\n```\nconst user = {\n name: 'Hedy Lamarr',\n imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',\n imageSize: 90,\n};\nexport default function Profile() {\n return (\n <>\n
{user.name}
\n \n >\n );\n}\n```\n\n Show more In the above example, \n\n```\nstyle={{}}\n```\n\n is not a special syntax, but a regular \n\n```\n{}\n```\n\n object inside the \n\n```\nstyle={ }\n```\n\n JSX curly braces. You can use the \n\n```\nstyle\n```\n\n attribute when your styles depend on JavaScript variables. Conditional rendering In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an \n\n```\nif\n```\n\n statement to conditionally include JSX: \n\n```\nlet content;if (isLoggedIn) { content = ;} else { content = ;}return (
{content}
);\n```\n\n If you prefer more compact code, you can use the conditional \n\n```\n?\n```\n\n operator. Unlike \n\n```\nif\n```\n\n, it works inside JSX: \n\n```\n
{isLoggedIn ? ( ) : ( )}
\n```\n\n When you don’t need the \n\n```\nelse\n```\n\n branch, you can also use a shorter logical \n\n```\n&&\n```\n\n syntax: \n\n```\n
{isLoggedIn && }
\n```\n\n All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always using \n\n```\nif...else\n```\n\n. Rendering lists You will rely on JavaScript features like \n\n```\nfor\n```\n\n loop and the array \n\n```\nmap()\n```\n\n function to render lists of components. For example, let’s say you have an array of products: \n\n```\nconst products = [ { title: 'Cabbage', id: 1 }, { title: 'Garlic', id: 2 }, { title: 'Apple', id: 3 },];\n```\n\n Inside your component, use the \n\n```\nmap()\n```\n\n function to transform an array of products into an array of \n\n```\n
\n```\n\n has a \n\n```\nkey\n```\n\n attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items. App. js App. js Reload Clear Fork \n\n```\nconst products = [\n { title: 'Cabbage', isFruit: false, id: 1 },\n { title: 'Garlic', isFruit: false, id: 2 },\n { title: 'Apple', isFruit: true, id: 3 },\n];\nexport default function ShoppingList() {\n const listItems = products.map(product =>\n
\n {product.title}\n
\n );\n return (\n
{listItems}
\n );\n}\n```\n\n Show more Responding to events You can respond to events by declaring event handler functions inside your components: \n\n```\nfunction MyButton() { function handleClick() { alert('You clicked me!'); } return ( );}\n```\n\n Notice how \n\n```\nonClick={handleClick}\n```\n\n has no parentheses at the end! Do not call the event handler function: you only need to pass it down. React will call your event handler when the user clicks the button. Updating the screen Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component. First, import \n\n```\nuseState\n```\n\n from React: \n\n```\nimport { useState } from 'react';\n```\n\n Now you can declare a state variable inside your component: \n\n```\nfunction MyButton() { const [count, setCount] = useState(0); // ...\n```\n\n You’ll get two things from \n\n```\nuseState\n```\n\n: the current state ( \n\n```\ncount\n```\n\n ), and the function that lets you update it ( \n\n```\nsetCount\n```\n\n ). You can give them any names, but the convention is to write \n\n```\n[something, setSomething]\n```\n\n. The first time the button is displayed, \n\n```\ncount\n```\n\n will be \n\n```\n0\n```\n\n because you passed \n\n```\n0\n```\n\n to \n\n```\nuseState()\n```\n\n. When you want to change state, call \n\n```\nsetCount()\n```\n\n and pass the new value to it. Clicking this button will increment the counter: \n\n```\nfunction MyButton() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( );}\n```\n\n React will call your component function again. This time, \n\n```\ncount\n```\n\n will be \n\n```\n1\n```\n\n. Then it will be \n\n```\n2\n```\n\n. And so on. If you render the same component multiple times, each will get its own state. Click each button separately: App. js App. js Reload Clear Fork \n\n```\nimport { useState } from 'react';\nexport default function MyApp() {\n return (\n
\n
Counters that update separately
\n \n \n
\n );\n}\nfunction MyButton() {\n const [count, setCount] = useState(0);\n function handleClick() {\n setCount(count + 1);\n }\n return (\n \n );\n}\n```\n\n Show more Notice how each button “remembers” its own \n\n```\ncount\n```\n\n state and doesn’t affect other buttons. Using Hooks Functions starting with \n\n```\nuse\n```\n\n are called Hooks. \n\n```\nuseState\n```\n\n is a built-in Hook provided by React. You can find other built-in Hooks in the API reference. You can also write your own Hooks by combining the existing ones. Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use \n\n```\nuseState\n```\n\n in a condition or a loop, extract a new component and put it there. Sharing data between components In the previous example, each \n\n```\nMyButton\n```\n\n had its own independent \n\n```\ncount\n```\n\n, and when each button was clicked, only the \n\n```\ncount\n```\n\n for the button clicked changed: Initially, each \n\n```\nMyButton\n```\n\n ’s \n\n```\ncount\n```\n\n state is \n\n```\n0\n```\n\n The first \n\n```\nMyButton\n```\n\n updates its \n\n```\ncount\n```\n\n to \n\n```\n1\n```\n\n However, often you’ll need components to share data and always update together. To make both \n\n```\nMyButton\n```\n\n components display the same \n\n```\ncount\n```\n\n and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them. In this example, it is \n\n```\nMyApp\n```\n\n: Initially, \n\n```\nMyApp\n```\n\n ’s \n\n```\ncount\n```\n\n state is \n\n```\n0\n```\n\n and is passed down to both children On click, \n\n```\nMyApp\n```\n\n updates its \n\n```\ncount\n```\n\n state to \n\n```\n1\n```\n\n and passes it down to both children Now when you click either button, the \n\n```\ncount\n```\n\n in \n\n```\nMyApp\n```\n\n will change, which will change both of the counts in \n\n```\nMyButton\n```\n\n. Here’s how you can express this in code. First, move the state up from \n\n```\nMyButton\n```\n\n into \n\n```\nMyApp\n```\n\n: \n\n```\nexport default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (
Counters that update separately
);}function MyButton() { // ... we're moving code from here ...}\n```\n\n Then, pass the state down from \n\n```\nMyApp\n```\n\n to each \n\n```\nMyButton\n```\n\n, together with the shared click handler. You can pass information to \n\n```\nMyButton\n```\n\n using the JSX curly braces, just like you previously did with built-in tags like \n\n```\n\n```\n\n: \n\n```\nexport default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (
Counters that update together
);}\n```\n\n The information you pass down like this is called props. Now the \n\n```\nMyApp\n```\n\n component contains the \n\n```\ncount\n```\n\n state and the \n\n```\nhandleClick\n```\n\n event handler, and passes both of them down as props to each of the buttons. Finally, change \n\n```\nMyButton\n```\n\n to read the props you have passed from its parent component: \n\n```\nfunction MyButton({ count, onClick }) { return ( );}\n```\n\n When you click the button, the \n\n```\nonClick\n```\n\n handler fires. Each button’s \n\n```\nonClick\n```\n\n prop was set to the \n\n```\nhandleClick\n```\n\n function inside \n\n```\nMyApp\n```\n\n, so the code inside of it runs. That code calls \n\n```\nsetCount(count + 1)\n```\n\n, incrementing the \n\n```\ncount\n```\n\n state variable. The new \n\n```\ncount\n```\n\n value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you’ve shared it between components. App. js App. js Reload Clear Fork \n\n```\nimport { useState } from 'react';\nexport default function MyApp() {\n const [count, setCount] = useState(0);\n function handleClick() {\n setCount(count + 1);\n }\n return (\n
\n
Counters that update together
\n \n \n
\n );\n}\nfunction MyButton({ count, onClick }) {\n return (\n \n );\n}\n```\n\n Show more Next Steps By now, you know the basics of how to write React code! Check out the Tutorial to put them into practice and build your first mini-app with React. Next Tutorial: Tic-Tac-Toe",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 2184,
- "timestamp": "2025-09-03 07:32:46"
- }
- },
- {
- "id": "91d495251548",
- "url": "https://react.dev/reference",
- "title": "React Reference Overview – React",
- "content": "API Reference React Reference Overview This section provides detailed reference documentation for working with React. For an introduction to React, please visit the Learn section. The React reference documentation is broken down into functional subsections: React Programmatic React features: Hooks - Use different React features from your components. Components - Built-in components that you can use in your JSX. APIs - APIs that are useful for defining components. Directives - Provide instructions to bundlers compatible with React Server Components. React DOM React-dom contains features that are only supported for web applications (which run in the browser DOM environment). This section is broken into the following: Hooks - Hooks for web applications which run in the browser DOM environment. Components - React supports all of the browser built-in HTML and SVG components. APIs - The \n\n```\nreact-dom\n```\n\n package contains methods supported only in web applications. Client APIs - The \n\n```\nreact-dom/client\n```\n\n APIs let you render React components on the client (in the browser). Server APIs - The \n\n```\nreact-dom/server\n```\n\n APIs let you render React components to HTML on the server. React Compiler The React Compiler is a build-time optimization tool that automatically memoizes your React components and values: Configuration - Configuration options for React Compiler. Directives - Function-level directives to control compilation. Compiling Libraries - Guide for shipping pre-compiled library code. Rules of React has idioms — or rules — for how to express patterns in a way that is easy to understand and yields high-quality applications: Components and Hooks must be pure – Purity makes your code easier to understand, debug, and allows React to automatically optimize your components and hooks correctly. React calls Components and Hooks – React is responsible for rendering components and hooks when necessary to optimize the user experience. Rules of Hooks – Hooks are defined using JavaScript functions, but they represent a special type of reusable UI logic with restrictions on where they can be called. Legacy APIs Legacy APIs - Exported from the \n\n```\nreact\n```\n\n package, but not recommended for use in newly written code. Next Hooks",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 347,
- "timestamp": "2025-09-03 07:32:46"
- }
- },
- {
- "id": "5a97a21efd5e",
- "url": "https://reactjs.org/docs/getting-started.html",
- "title": "Quick Start – React",
- "content": "Learn React Quick Start Welcome to the React documentation! This page will give you an introduction to 80% of the React concepts that you will use on a daily basis. You will learn How to create and nest components How to add markup and styles How to display data How to render conditions and lists How to respond to events and update the screen How to share data between components Creating and nesting components React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page. React components are JavaScript functions that return markup: \n\n```\nfunction MyButton() { return ( );}\n```\n\n Now that you’ve declared \n\n```\nMyButton\n```\n\n, you can nest it into another component: \n\n```\nexport default function MyApp() { return (
Welcome to my app
);}\n```\n\n Notice that \n\n```\n\n```\n\n starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase. Have a look at the result: App. js App. js Reload Clear Fork \n\n```\nfunction MyButton() {\n return (\n \n );\n}\nexport default function MyApp() {\n return (\n
\n
Welcome to my app
\n \n
\n );\n}\n```\n\n Show more The \n\n```\nexport default\n```\n\n keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, MDN and javascript. info have great references. Writing markup with JSX The markup syntax you’ve seen above is called JSX. It is optional, but most React projects use JSX for its convenience. All of the tools we recommend for local development support JSX out of the box. JSX is stricter than HTML. You have to close tags like \n\n```\n \n```\n\n. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a \n\n```\n
...
\n```\n\n or an empty \n\n```\n<>...>\n```\n\n wrapper: \n\n```\nfunction AboutPage() { return ( <>
About
Hello there. How do you do?
> );}\n```\n\n If you have a lot of HTML to port to JSX, you can use an online converter. Adding styles In React, you specify a CSS class with \n\n```\nclassName\n```\n\n. It works the same way as the HTML \n\n```\nclass\n```\n\n attribute: \n\n```\n\n```\n\n Then you write the CSS rules for it in a separate CSS file: \n\n```\n/* In your CSS */.avatar { border-radius: 50%;}\n```\n\n React does not prescribe how you add CSS files. In the simplest case, you’ll add a \n\n```\n\n```\n\n tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project. Displaying data JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display \n\n```\nuser.name\n```\n\n: \n\n```\nreturn (
{user.name}
);\n```\n\n You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, \n\n```\nclassName=\"avatar\"\n```\n\n passes the \n\n```\n\"avatar\"\n```\n\n string as the CSS class, but \n\n```\nsrc={user.imageUrl}\n```\n\n reads the JavaScript \n\n```\nuser.imageUrl\n```\n\n variable value, and then passes that value as the \n\n```\nsrc\n```\n\n attribute: \n\n```\nreturn ( );\n```\n\n You can put more complex expressions inside the JSX curly braces too, for example, string concatenation: App. js App. js Reload Clear Fork \n\n```\nconst user = {\n name: 'Hedy Lamarr',\n imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',\n imageSize: 90,\n};\nexport default function Profile() {\n return (\n <>\n
{user.name}
\n \n >\n );\n}\n```\n\n Show more In the above example, \n\n```\nstyle={{}}\n```\n\n is not a special syntax, but a regular \n\n```\n{}\n```\n\n object inside the \n\n```\nstyle={ }\n```\n\n JSX curly braces. You can use the \n\n```\nstyle\n```\n\n attribute when your styles depend on JavaScript variables. Conditional rendering In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an \n\n```\nif\n```\n\n statement to conditionally include JSX: \n\n```\nlet content;if (isLoggedIn) { content = ;} else { content = ;}return (
{content}
);\n```\n\n If you prefer more compact code, you can use the conditional \n\n```\n?\n```\n\n operator. Unlike \n\n```\nif\n```\n\n, it works inside JSX: \n\n```\n
{isLoggedIn ? ( ) : ( )}
\n```\n\n When you don’t need the \n\n```\nelse\n```\n\n branch, you can also use a shorter logical \n\n```\n&&\n```\n\n syntax: \n\n```\n
{isLoggedIn && }
\n```\n\n All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always using \n\n```\nif...else\n```\n\n. Rendering lists You will rely on JavaScript features like \n\n```\nfor\n```\n\n loop and the array \n\n```\nmap()\n```\n\n function to render lists of components. For example, let’s say you have an array of products: \n\n```\nconst products = [ { title: 'Cabbage', id: 1 }, { title: 'Garlic', id: 2 }, { title: 'Apple', id: 3 },];\n```\n\n Inside your component, use the \n\n```\nmap()\n```\n\n function to transform an array of products into an array of \n\n```\n
\n```\n\n has a \n\n```\nkey\n```\n\n attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items. App. js App. js Reload Clear Fork \n\n```\nconst products = [\n { title: 'Cabbage', isFruit: false, id: 1 },\n { title: 'Garlic', isFruit: false, id: 2 },\n { title: 'Apple', isFruit: true, id: 3 },\n];\nexport default function ShoppingList() {\n const listItems = products.map(product =>\n
\n {product.title}\n
\n );\n return (\n
{listItems}
\n );\n}\n```\n\n Show more Responding to events You can respond to events by declaring event handler functions inside your components: \n\n```\nfunction MyButton() { function handleClick() { alert('You clicked me!'); } return ( );}\n```\n\n Notice how \n\n```\nonClick={handleClick}\n```\n\n has no parentheses at the end! Do not call the event handler function: you only need to pass it down. React will call your event handler when the user clicks the button. Updating the screen Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component. First, import \n\n```\nuseState\n```\n\n from React: \n\n```\nimport { useState } from 'react';\n```\n\n Now you can declare a state variable inside your component: \n\n```\nfunction MyButton() { const [count, setCount] = useState(0); // ...\n```\n\n You’ll get two things from \n\n```\nuseState\n```\n\n: the current state ( \n\n```\ncount\n```\n\n ), and the function that lets you update it ( \n\n```\nsetCount\n```\n\n ). You can give them any names, but the convention is to write \n\n```\n[something, setSomething]\n```\n\n. The first time the button is displayed, \n\n```\ncount\n```\n\n will be \n\n```\n0\n```\n\n because you passed \n\n```\n0\n```\n\n to \n\n```\nuseState()\n```\n\n. When you want to change state, call \n\n```\nsetCount()\n```\n\n and pass the new value to it. Clicking this button will increment the counter: \n\n```\nfunction MyButton() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( );}\n```\n\n React will call your component function again. This time, \n\n```\ncount\n```\n\n will be \n\n```\n1\n```\n\n. Then it will be \n\n```\n2\n```\n\n. And so on. If you render the same component multiple times, each will get its own state. Click each button separately: App. js App. js Reload Clear Fork \n\n```\nimport { useState } from 'react';\nexport default function MyApp() {\n return (\n
\n
Counters that update separately
\n \n \n
\n );\n}\nfunction MyButton() {\n const [count, setCount] = useState(0);\n function handleClick() {\n setCount(count + 1);\n }\n return (\n \n );\n}\n```\n\n Show more Notice how each button “remembers” its own \n\n```\ncount\n```\n\n state and doesn’t affect other buttons. Using Hooks Functions starting with \n\n```\nuse\n```\n\n are called Hooks. \n\n```\nuseState\n```\n\n is a built-in Hook provided by React. You can find other built-in Hooks in the API reference. You can also write your own Hooks by combining the existing ones. Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use \n\n```\nuseState\n```\n\n in a condition or a loop, extract a new component and put it there. Sharing data between components In the previous example, each \n\n```\nMyButton\n```\n\n had its own independent \n\n```\ncount\n```\n\n, and when each button was clicked, only the \n\n```\ncount\n```\n\n for the button clicked changed: Initially, each \n\n```\nMyButton\n```\n\n ’s \n\n```\ncount\n```\n\n state is \n\n```\n0\n```\n\n The first \n\n```\nMyButton\n```\n\n updates its \n\n```\ncount\n```\n\n to \n\n```\n1\n```\n\n However, often you’ll need components to share data and always update together. To make both \n\n```\nMyButton\n```\n\n components display the same \n\n```\ncount\n```\n\n and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them. In this example, it is \n\n```\nMyApp\n```\n\n: Initially, \n\n```\nMyApp\n```\n\n ’s \n\n```\ncount\n```\n\n state is \n\n```\n0\n```\n\n and is passed down to both children On click, \n\n```\nMyApp\n```\n\n updates its \n\n```\ncount\n```\n\n state to \n\n```\n1\n```\n\n and passes it down to both children Now when you click either button, the \n\n```\ncount\n```\n\n in \n\n```\nMyApp\n```\n\n will change, which will change both of the counts in \n\n```\nMyButton\n```\n\n. Here’s how you can express this in code. First, move the state up from \n\n```\nMyButton\n```\n\n into \n\n```\nMyApp\n```\n\n: \n\n```\nexport default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (
Counters that update separately
);}function MyButton() { // ... we're moving code from here ...}\n```\n\n Then, pass the state down from \n\n```\nMyApp\n```\n\n to each \n\n```\nMyButton\n```\n\n, together with the shared click handler. You can pass information to \n\n```\nMyButton\n```\n\n using the JSX curly braces, just like you previously did with built-in tags like \n\n```\n\n```\n\n: \n\n```\nexport default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (
Counters that update together
);}\n```\n\n The information you pass down like this is called props. Now the \n\n```\nMyApp\n```\n\n component contains the \n\n```\ncount\n```\n\n state and the \n\n```\nhandleClick\n```\n\n event handler, and passes both of them down as props to each of the buttons. Finally, change \n\n```\nMyButton\n```\n\n to read the props you have passed from its parent component: \n\n```\nfunction MyButton({ count, onClick }) { return ( );}\n```\n\n When you click the button, the \n\n```\nonClick\n```\n\n handler fires. Each button’s \n\n```\nonClick\n```\n\n prop was set to the \n\n```\nhandleClick\n```\n\n function inside \n\n```\nMyApp\n```\n\n, so the code inside of it runs. That code calls \n\n```\nsetCount(count + 1)\n```\n\n, incrementing the \n\n```\ncount\n```\n\n state variable. The new \n\n```\ncount\n```\n\n value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you’ve shared it between components. App. js App. js Reload Clear Fork \n\n```\nimport { useState } from 'react';\nexport default function MyApp() {\n const [count, setCount] = useState(0);\n function handleClick() {\n setCount(count + 1);\n }\n return (\n
\n
Counters that update together
\n \n \n
\n );\n}\nfunction MyButton({ count, onClick }) {\n return (\n \n );\n}\n```\n\n Show more Next Steps By now, you know the basics of how to write React code! Check out the Tutorial to put them into practice and build your first mini-app with React. Next Tutorial: Tic-Tac-Toe",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 2184,
- "timestamp": "2025-09-03 07:32:46"
- }
- },
- {
- "id": "3bb87b3dbc3f",
- "url": "https://overreacted.io/",
- "title": "overreacted — A blog by Dan Abramov",
- "content": "Lean for JavaScript Developers September 2, 2025 Programming with proofs. Beyond Booleans August 16, 2025 What is the type of 2 + 2 = 4? The Math Is Haunted July 30, 2025 A taste of Lean. Suppressions of Suppressions June 11, 2025 I heard you like linting. I'm Doing a Little Consulting June 11, 2025 Personal update post. How Imports Work in RSC June 5, 2025 A layered module system. RSC for LISP Developers June 1, 2025 Quoting for modules. Progressive JSON May 31, 2025 Why streaming isn't enough. Why Does RSC Integrate with a Bundler? May 30, 2025 One does not simply serialize a module. One Roundtrip Per Navigation May 29, 2025 What do HTML, GraphQL, and RSC have in common? Static as a Server May 8, 2025 You wouldn't download a site. RSC for Astro Developers May 6, 2025 Islands, but make it fractal. Functional HTML May 2, 2025 Tags on both sides. What Does \"use client\" Do? April 25, 2025 Two worlds, two doors. Impossible Components April 22, 2025 Composing across the stack. JSX Over The Wire April 16, 2025 Turning your API inside-out. React for Two Computers April 9, 2025 Two things, one origin. The Two Reacts January 4, 2024 UI = f(data)(state) A Chain Reaction December 11, 2023 The limits of my language mean the limits of my world. npm audit: Broken by Design July 7, 2021 Found 99 vulnerabilities (84 moderately irrelevant, 15 highly irrelevant) Before You memo() February 23, 2021 Rendering optimizations that come naturally. The WET Codebase July 13, 2020 Come waste your time with me. Goodbye, Clean Code January 11, 2020 Let clean code guide you. Then let it go. My Decade in Review January 1, 2020 A personal reflection. What Are the React Team Principles? December 25, 2019 UI Before API. On let vs const December 22, 2019 So which one should I use? What Is JavaScript Made Of? December 20, 2019 Getting a closure on JavaScript. How Does the Development Mode Work? August 4, 2019 Dead code elimination by convention. Algebraic Effects for the Rest of Us July 21, 2019 They’re not burritos. Preparing for a Tech Talk, Part 3: Content July 10, 2019 Turning an idea into a talk. Name It, and They Will Come March 25, 2019 A change starts with a story. Writing Resilient Components March 16, 2019 Four principles to set you on the right path. A Complete Guide to useEffect March 9, 2019 Effects are a part of your data flow. How Are Function Components Different from Classes? March 3, 2019 They’re a whole different Pokémon. Coping with Feedback March 2, 2019 Sometimes I can’t fall asleep. Fix Like No One’s Watching February 15, 2019 The other kind of technical debt. Making setInterval Declarative with React Hooks February 4, 2019 How I learned to stop worrying and love refs. React as a UI Runtime February 2, 2019 An in-depth description of the React programming model. Why Isn’t X a Hook? January 26, 2019 Just because we can, doesn’t mean we should. The “Bug-O” Notation January 25, 2019 What is the 🐞(n) of your API? Preparing for a Tech Talk, Part 2: What, Why, and How January 7, 2019 We need to go deeper. The Elements of UI Engineering December 30, 2018 What makes UI engineering difficult? Things I Don’t Know as of 2018 December 28, 2018 We can admit our knowledge gaps without devaluing our expertise. Preparing for a Tech Talk, Part 1: Motivation December 26, 2018 Here’s my recipe for a good talk idea. Why Do React Hooks Rely on Call Order? December 13, 2018 Lessons learned from mixins, render props, HOCs, and classes. Optimized for Change December 12, 2018 What makes a great API? How Does setState Know What to Do? December 9, 2018 Dependency injection is nice if you don’t have to think about it. My Wishlist for Hot Reloading December 8, 2018 I don't want a lot for Christmas. There is just one thing I need. Why Do React Elements Have a $$typeof Property? December 3, 2018 It has something to do with security. How Does React Tell a Class from a Function? December 2, 2018 We talk about classes, new, instanceof, prototype chains, and API design. Why Do We Write super(props)? November 30, 2018 There’s a twist at the end.",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.5,
- "coherence_score": 6.0,
- "word_count": 721,
- "timestamp": "2025-09-03 07:32:46"
- }
- },
- {
- "id": "3c91f6c3070d",
- "url": "https://beta.reactjs.org/learn",
- "title": "Quick Start – React",
- "content": "Learn React Quick Start Welcome to the React documentation! This page will give you an introduction to 80% of the React concepts that you will use on a daily basis. You will learn How to create and nest components How to add markup and styles How to display data How to render conditions and lists How to respond to events and update the screen How to share data between components Creating and nesting components React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page. React components are JavaScript functions that return markup: \n\n```\nfunction MyButton() { return ( );}\n```\n\n Now that you’ve declared \n\n```\nMyButton\n```\n\n, you can nest it into another component: \n\n```\nexport default function MyApp() { return (
Welcome to my app
);}\n```\n\n Notice that \n\n```\n\n```\n\n starts with a capital letter. That’s how you know it’s a React component. React component names must always start with a capital letter, while HTML tags must be lowercase. Have a look at the result: App. js App. js Reload Clear Fork \n\n```\nfunction MyButton() {\n return (\n \n );\n}\nexport default function MyApp() {\n return (\n
\n
Welcome to my app
\n \n
\n );\n}\n```\n\n Show more The \n\n```\nexport default\n```\n\n keywords specify the main component in the file. If you’re not familiar with some piece of JavaScript syntax, MDN and javascript. info have great references. Writing markup with JSX The markup syntax you’ve seen above is called JSX. It is optional, but most React projects use JSX for its convenience. All of the tools we recommend for local development support JSX out of the box. JSX is stricter than HTML. You have to close tags like \n\n```\n \n```\n\n. Your component also can’t return multiple JSX tags. You have to wrap them into a shared parent, like a \n\n```\n
...
\n```\n\n or an empty \n\n```\n<>...>\n```\n\n wrapper: \n\n```\nfunction AboutPage() { return ( <>
About
Hello there. How do you do?
> );}\n```\n\n If you have a lot of HTML to port to JSX, you can use an online converter. Adding styles In React, you specify a CSS class with \n\n```\nclassName\n```\n\n. It works the same way as the HTML \n\n```\nclass\n```\n\n attribute: \n\n```\n\n```\n\n Then you write the CSS rules for it in a separate CSS file: \n\n```\n/* In your CSS */.avatar { border-radius: 50%;}\n```\n\n React does not prescribe how you add CSS files. In the simplest case, you’ll add a \n\n```\n\n```\n\n tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project. Displaying data JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display \n\n```\nuser.name\n```\n\n: \n\n```\nreturn (
{user.name}
);\n```\n\n You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, \n\n```\nclassName=\"avatar\"\n```\n\n passes the \n\n```\n\"avatar\"\n```\n\n string as the CSS class, but \n\n```\nsrc={user.imageUrl}\n```\n\n reads the JavaScript \n\n```\nuser.imageUrl\n```\n\n variable value, and then passes that value as the \n\n```\nsrc\n```\n\n attribute: \n\n```\nreturn ( );\n```\n\n You can put more complex expressions inside the JSX curly braces too, for example, string concatenation: App. js App. js Reload Clear Fork \n\n```\nconst user = {\n name: 'Hedy Lamarr',\n imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',\n imageSize: 90,\n};\nexport default function Profile() {\n return (\n <>\n
{user.name}
\n \n >\n );\n}\n```\n\n Show more In the above example, \n\n```\nstyle={{}}\n```\n\n is not a special syntax, but a regular \n\n```\n{}\n```\n\n object inside the \n\n```\nstyle={ }\n```\n\n JSX curly braces. You can use the \n\n```\nstyle\n```\n\n attribute when your styles depend on JavaScript variables. Conditional rendering In React, there is no special syntax for writing conditions. Instead, you’ll use the same techniques as you use when writing regular JavaScript code. For example, you can use an \n\n```\nif\n```\n\n statement to conditionally include JSX: \n\n```\nlet content;if (isLoggedIn) { content = ;} else { content = ;}return (
{content}
);\n```\n\n If you prefer more compact code, you can use the conditional \n\n```\n?\n```\n\n operator. Unlike \n\n```\nif\n```\n\n, it works inside JSX: \n\n```\n
{isLoggedIn ? ( ) : ( )}
\n```\n\n When you don’t need the \n\n```\nelse\n```\n\n branch, you can also use a shorter logical \n\n```\n&&\n```\n\n syntax: \n\n```\n
{isLoggedIn && }
\n```\n\n All of these approaches also work for conditionally specifying attributes. If you’re unfamiliar with some of this JavaScript syntax, you can start by always using \n\n```\nif...else\n```\n\n. Rendering lists You will rely on JavaScript features like \n\n```\nfor\n```\n\n loop and the array \n\n```\nmap()\n```\n\n function to render lists of components. For example, let’s say you have an array of products: \n\n```\nconst products = [ { title: 'Cabbage', id: 1 }, { title: 'Garlic', id: 2 }, { title: 'Apple', id: 3 },];\n```\n\n Inside your component, use the \n\n```\nmap()\n```\n\n function to transform an array of products into an array of \n\n```\n
\n```\n\n has a \n\n```\nkey\n```\n\n attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items. App. js App. js Reload Clear Fork \n\n```\nconst products = [\n { title: 'Cabbage', isFruit: false, id: 1 },\n { title: 'Garlic', isFruit: false, id: 2 },\n { title: 'Apple', isFruit: true, id: 3 },\n];\nexport default function ShoppingList() {\n const listItems = products.map(product =>\n
\n {product.title}\n
\n );\n return (\n
{listItems}
\n );\n}\n```\n\n Show more Responding to events You can respond to events by declaring event handler functions inside your components: \n\n```\nfunction MyButton() { function handleClick() { alert('You clicked me!'); } return ( );}\n```\n\n Notice how \n\n```\nonClick={handleClick}\n```\n\n has no parentheses at the end! Do not call the event handler function: you only need to pass it down. React will call your event handler when the user clicks the button. Updating the screen Often, you’ll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component. First, import \n\n```\nuseState\n```\n\n from React: \n\n```\nimport { useState } from 'react';\n```\n\n Now you can declare a state variable inside your component: \n\n```\nfunction MyButton() { const [count, setCount] = useState(0); // ...\n```\n\n You’ll get two things from \n\n```\nuseState\n```\n\n: the current state ( \n\n```\ncount\n```\n\n ), and the function that lets you update it ( \n\n```\nsetCount\n```\n\n ). You can give them any names, but the convention is to write \n\n```\n[something, setSomething]\n```\n\n. The first time the button is displayed, \n\n```\ncount\n```\n\n will be \n\n```\n0\n```\n\n because you passed \n\n```\n0\n```\n\n to \n\n```\nuseState()\n```\n\n. When you want to change state, call \n\n```\nsetCount()\n```\n\n and pass the new value to it. Clicking this button will increment the counter: \n\n```\nfunction MyButton() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( );}\n```\n\n React will call your component function again. This time, \n\n```\ncount\n```\n\n will be \n\n```\n1\n```\n\n. Then it will be \n\n```\n2\n```\n\n. And so on. If you render the same component multiple times, each will get its own state. Click each button separately: App. js App. js Reload Clear Fork \n\n```\nimport { useState } from 'react';\nexport default function MyApp() {\n return (\n
\n
Counters that update separately
\n \n \n
\n );\n}\nfunction MyButton() {\n const [count, setCount] = useState(0);\n function handleClick() {\n setCount(count + 1);\n }\n return (\n \n );\n}\n```\n\n Show more Notice how each button “remembers” its own \n\n```\ncount\n```\n\n state and doesn’t affect other buttons. Using Hooks Functions starting with \n\n```\nuse\n```\n\n are called Hooks. \n\n```\nuseState\n```\n\n is a built-in Hook provided by React. You can find other built-in Hooks in the API reference. You can also write your own Hooks by combining the existing ones. Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use \n\n```\nuseState\n```\n\n in a condition or a loop, extract a new component and put it there. Sharing data between components In the previous example, each \n\n```\nMyButton\n```\n\n had its own independent \n\n```\ncount\n```\n\n, and when each button was clicked, only the \n\n```\ncount\n```\n\n for the button clicked changed: Initially, each \n\n```\nMyButton\n```\n\n ’s \n\n```\ncount\n```\n\n state is \n\n```\n0\n```\n\n The first \n\n```\nMyButton\n```\n\n updates its \n\n```\ncount\n```\n\n to \n\n```\n1\n```\n\n However, often you’ll need components to share data and always update together. To make both \n\n```\nMyButton\n```\n\n components display the same \n\n```\ncount\n```\n\n and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them. In this example, it is \n\n```\nMyApp\n```\n\n: Initially, \n\n```\nMyApp\n```\n\n ’s \n\n```\ncount\n```\n\n state is \n\n```\n0\n```\n\n and is passed down to both children On click, \n\n```\nMyApp\n```\n\n updates its \n\n```\ncount\n```\n\n state to \n\n```\n1\n```\n\n and passes it down to both children Now when you click either button, the \n\n```\ncount\n```\n\n in \n\n```\nMyApp\n```\n\n will change, which will change both of the counts in \n\n```\nMyButton\n```\n\n. Here’s how you can express this in code. First, move the state up from \n\n```\nMyButton\n```\n\n into \n\n```\nMyApp\n```\n\n: \n\n```\nexport default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (
Counters that update separately
);}function MyButton() { // ... we're moving code from here ...}\n```\n\n Then, pass the state down from \n\n```\nMyApp\n```\n\n to each \n\n```\nMyButton\n```\n\n, together with the shared click handler. You can pass information to \n\n```\nMyButton\n```\n\n using the JSX curly braces, just like you previously did with built-in tags like \n\n```\n\n```\n\n: \n\n```\nexport default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (
Counters that update together
);}\n```\n\n The information you pass down like this is called props. Now the \n\n```\nMyApp\n```\n\n component contains the \n\n```\ncount\n```\n\n state and the \n\n```\nhandleClick\n```\n\n event handler, and passes both of them down as props to each of the buttons. Finally, change \n\n```\nMyButton\n```\n\n to read the props you have passed from its parent component: \n\n```\nfunction MyButton({ count, onClick }) { return ( );}\n```\n\n When you click the button, the \n\n```\nonClick\n```\n\n handler fires. Each button’s \n\n```\nonClick\n```\n\n prop was set to the \n\n```\nhandleClick\n```\n\n function inside \n\n```\nMyApp\n```\n\n, so the code inside of it runs. That code calls \n\n```\nsetCount(count + 1)\n```\n\n, incrementing the \n\n```\ncount\n```\n\n state variable. The new \n\n```\ncount\n```\n\n value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you’ve shared it between components. App. js App. js Reload Clear Fork \n\n```\nimport { useState } from 'react';\nexport default function MyApp() {\n const [count, setCount] = useState(0);\n function handleClick() {\n setCount(count + 1);\n }\n return (\n
\n
Counters that update together
\n \n \n
\n );\n}\nfunction MyButton({ count, onClick }) {\n return (\n \n );\n}\n```\n\n Show more Next Steps By now, you know the basics of how to write React code! Check out the Tutorial to put them into practice and build your first mini-app with React. Next Tutorial: Tic-Tac-Toe",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 2184,
- "timestamp": "2025-09-03 07:32:46"
- }
- },
- {
- "id": "5f4eea061c8d",
- "url": "https://stackoverflow.com/questions/32646920/whats-the-at-symbol-in-the-redux-connect-decorator",
- "title": "javascript - What's the '@' (at symbol) in the Redux @connect decorator? - Stack Overflow",
- "content": "What's the '@' (at symbol) in the Redux @connect decorator? Ask Question Asked 9 years, 11 months ago Modified 8 years ago Viewed 68k times 238 I am learning Redux with React and stumbled upon this code. I am not sure if it is Redux specific or not, but I have seen the following code snippet in one of the examples. \n\n```\n@connect((state) => {\n return {\n key: state.a.b\n };\n})\n```\n\n While the functionality of \n\n```\nconnect\n```\n\n is pretty straightforward, but I don't understand the \n\n```\n@\n```\n\n before \n\n```\nconnect\n```\n\n. It isn't even a JavaScript operator if I am not wrong. Can someone explain please what is this and why is it used? Update: It is in fact a part of \n\n```\nreact-redux\n```\n\n which is used to connects a React component to a Redux store. javascript reactjs decorator redux Share Improve this question Follow edited Jun 11, 2016 at 4: 35 Felix Kling 819k 181 181 gold badges 1. 1k 1. 1k silver badges 1. 2k 1. 2k bronze badges asked Sep 18, 2015 at 8: 07 Salman 9, 467 6 6 gold badges 42 42 silver badges 74 74 bronze badges 4 6 I'm not familiar with Redux, but it looks like a decorator. medium. com/google-developers/… Lee – Lee 09/18/2015 08: 19: 52 Commented Sep 18, 2015 at 8: 19 4 I love how in this new JavaScript world you are staring at the code half of the time and thinking \"what part of the language syntax is this? \" MK. – MK. 11/29/2016 05: 11: 03 Commented Nov 29, 2016 at 5: 11 4 Lol, I'm way deep into redux and stuff now. But back then I didn't know the decorator syntax has nothing to do with redux. Its just JavaScript. Glad to see this question is helping a lot of people like me.: ) Salman – Salman 11/29/2016 12: 16: 55 Commented Nov 29, 2016 at 12: 16 1 Apparently the redux team discourages the use of connect as a decorator at the moment github. com/happypoulp/redux-tutorial/issues/87 Syed Jafri – Syed Jafri 02/26/2017 22: 15: 07 Commented Feb 26, 2017 at 22: 15 Add a comment | 2 Answers 2 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 384 The \n\n```\n@\n```\n\n symbol is in fact a JavaScript expression currently proposed to signify decorators: Decorators make it possible to annotate and modify classes and properties at design time. Here's an example of setting up Redux without and with a decorator: Without a decorator \n\n```\nimport React from 'react';\nimport * as actionCreators from './actionCreators';\nimport { bindActionCreators } from 'redux';\nimport { connect } from 'react-redux';\nfunction mapStateToProps(state) {\n return { todos: state.todos };\n}\nfunction mapDispatchToProps(dispatch) {\n return { actions: bindActionCreators(actionCreators, dispatch) };\n}\nclass MyApp extends React.Component {\n // ...define your main app here\n}\nexport default connect(mapStateToProps, mapDispatchToProps)(MyApp);\n```\n\n Using a decorator \n\n```\nimport React from 'react';\nimport * as actionCreators from './actionCreators';\nimport { bindActionCreators } from 'redux';\nimport { connect } from 'react-redux';\nfunction mapStateToProps(state) {\n return { todos: state.todos };\n}\nfunction mapDispatchToProps(dispatch) {\n return { actions: bindActionCreators(actionCreators, dispatch) };\n}\n@connect(mapStateToProps, mapDispatchToProps)\nexport default class MyApp extends React.Component {\n // ...define your main app here\n}\n```\n\n Both examples above are equivalent, it's just a matter of preference. Also, the decorator syntax isn't built into any Javascript runtimes yet, and is still experimental and subject to change. If you want to use it, it is available using Babel. Share Improve this answer Follow edited Jun 11, 2016 at 4: 31 Felix Kling 819k 181 181 gold badges 1. 1k 1. 1k silver badges 1. 2k 1. 2k bronze badges answered Sep 20, 2015 at 4: 56 Tanner Semerad Tanner Semerad 12. 7k 12 12 gold badges 43 43 silver badges 51 51 bronze badges 7 2 One can even be more terse with ES6 syntax. @connect( state = > { return { todos: state. todos }; }, dispatch = > { return {actions: bindActionCreators(actionCreators, dispatch)}; } ) LessQuesar – LessQuesar 10/24/2016 17: 46: 53 Commented Oct 24, 2016 at 17: 46 11 If you really want to be terse you can use implicit returns in ES6. It depends on how explicit you want to be. \n\n```\n@connect(state => ({todos: state.todos}), dispatch => ({actions: bindActionCreators(actionCreators, dispatch)}))\n```\n\n Tanner Semerad – Tanner Semerad 10/24/2016 18: 22: 09 Commented Oct 24, 2016 at 18: 22 3 How would you export the unconnected component for unit testing? tim – tim 04/13/2017 09: 30: 13 Commented Apr 13, 2017 at 9: 30 Using decorator for redux with react-navigation can be problematic, current best-practice is to use the function not the decorator: github. com/react-community/react-navigation/issues/1180 straya – straya 05/23/2017 03: 02: 16 Commented May 23, 2017 at 3: 02 The examples are really helpful Subhadeep Banerjee – Subhadeep Banerjee 06/27/2018 14: 16: 42 Commented Jun 27, 2018 at 14: 16 | Show 2 more comments 51 Very Important! These props are called state props and they are different from normal props, any change to your component state props will trigger the component render method again and again even if you don't use these props so for Performance Reasons try to bind to your component only the state props that you need inside your component and if you use a sub props only bind these props. example: lets say inside your component you only need two props: the last message the user name don't do this \n\n```\n@connect(state => ({ \n user: state.user,\n messages: state.messages\n}))\n```\n\n do this \n\n```\n@connect(state => ({ \n user_name: state.user.name,\n last_message: state.messages[state.messages.length-1]\n}))\n```\n\n Share Improve this answer Follow answered Apr 9, 2017 at 16: 53 Fareed Alnamrouti Fareed Alnamrouti 32. 3k 4 4 gold badges 90 90 silver badges 78 78 bronze badges 2 9 or use selectors like reselect or fastmemoize Julius Koronci – Julius Koronci 06/29/2017 06: 39: 25 Commented Jun 29, 2017 at 6: 39 survivejs. com/react/appendices/understanding-decorators and sitepoint. com/javascript-decorators-what-they-are zloctb – zloctb 10/29/2017 08: 52: 29 Commented Oct 29, 2017 at 8: 52 Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript reactjs decorator redux See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 1 using higher order component in react class component 0 What does the '@' sign in front of a function do? 2 React-redux @connect does not work, but connect() does 4 react. js get child value in parent component 0 Building React/Redux Application 0 Which way should I use for Connector in Redux? 1 React Native Redux Reducer not working 0 Adding new item to array using spread operator in react redux not re-rendering the component Related 78 What does the at symbol (@) do in ES6 javascript? (ECMAScript 2015) 13 What is the use of @connect decorator in react-redux 0 why @ syntax is not working in react js 16 What is the @ symbol in TypeScript? 6 React-Redux @connect syntax error 0 Uable to understand function with @ symbol in react component 0 deciphering a export default connect statement in a react component 45 What does the @ symbol mean in a react import statement 0 Understanding the syntax of connect() function in react-redux 2 what is @ in react HOC? Hot Network Questions What did Jesus eat in relationship to his Jewish culture and tradition? Looking for a short story collection, history of the universe starting with the big bang Would this weapon be good for catching melee weapons? Do the Apollo probe/drogues also serve as an airtight seal when not docked, or is there a separate seal? Does the age limit for U. S. presidents apply at the the time of election or swearing in? PF2e: Raising a shield out of combat What do I do if a DB Bahn train is late for an OBB connection? Co-Lead Role Undermined, Manager Dismissive Comparative law: Does a lease transfer all benefits at once or gradually? Does Innate Sorcery grant Advantage to True Strike? How to prove that natural number less than is irrelevant? french interferes with iso time display What are the biblical arguments against the idea of a post-mortem opportunity for salvation? What should an airline pilot do in a decompression with a MEA of FL200? Did the Apollo Command Module launch with the docking probe already in place? Have there been any 20th century onwards notable rabbanim from the Indian Jewish community? How to merge two tables with a different amount of columns in one table? 90-00s TV show. Colony established on a habitable planet. Colony is surrounded by a large wall. Expedition outside the wall encounter exiled group c++ format_to verbosity Why is cinnamic acid nitrated at the ortho, para positions and not the meta position? What is the measure of the new angle? In \"Little Women\" (1949), what is the German song sung and played on the piano by Professor Bhaer? How can I attach the bottom of a window A. C. unit to the bottom of a window? Is it correct for a rotating uniform charged ring to have current? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 1640,
- "timestamp": "2025-09-03 07:33:08"
- }
- },
- {
- "id": "aea45a48b743",
- "url": "https://stackoverflow.com/questions/53389956/how-to-test-a-classname-with-the-jest-and-react-testing-library",
- "title": "javascript - How to test a className with the Jest and React testing library - Stack Overflow",
- "content": "How to test a className with the Jest and React testing library Ask Question Asked 6 years, 9 months ago Modified 1 year, 8 months ago Viewed 477k times 194 I am totally new to JavaScript testing and am working in a new codebase. I would like to write a test that is checking for a className on the element. I am working with Jest and React Testing Library. Below I have a test that will render a button based on the \n\n```\nvariant\n```\n\n prop. It also contains a className and I would like to test that. \n\n```\nit('Renders with a className equal to the variant', () => {\n const { container } = render()\n expect(container.firstChild) // Check for className here\n})\n```\n\n I tried to google for a property like Enzyme has with \n\n```\nhasClass\n```\n\n, but I couldn't find anything. How can I solve this with the current libraries ( React Testing Library and Jest)? javascript reactjs jestjs react-testing-library Share Improve this question Follow edited Jan 29, 2021 at 14: 21 Peter Mortensen 31. 6k 22 22 gold badges 110 110 silver badges 134 134 bronze badges asked Nov 20, 2018 at 9: 31 Giesburts 7, 796 17 17 gold badges 52 52 silver badges 92 92 bronze badges 3 5 Following up on @AnonymousSB comment, Enzyme is great if you're more concerned with testing implementation, whereas the React Testing Library is for those taking a more user behavior-centric approach to testing. James B. Nall – James B. Nall 07/14/2020 14: 19: 47 Commented Jul 14, 2020 at 14: 19 2 Following up on both of these - developers considering using Enzyme in a new project should note that, according to Enzyme's docs, it only supports up to React 16. There do not appear to be plans to upgrade to support current versions of React. More info at dev. to/wojtekmaj/enzyme-is-dead-now-what-ekl Andrew – Andrew 03/21/2022 17: 09: 50 Commented Mar 21, 2022 at 17: 09 @AnonymousSB and JamesB. Nall I think they don't include a getByClassName so that people move away from the \"className is identifier\" logic. I have worked extensively with Enzyme, and that's what I used to use. Rather, use some other means to get the element (how a user would find it in the page) and then check for a specific class in that container based on some conditions (e. g. \"active\" if a specific prop is set) cst1992 – cst1992 09/01/2022 08: 44: 59 Commented Sep 1, 2022 at 8: 44 Add a comment | 10 Answers 10 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 238 You can easily do that with react-testing-library. First, you have to understand that \n\n```\ncontainer\n```\n\n or the result of \n\n```\ngetByText\n```\n\n etc. are merely DOM nodes. You can interact with them in the same way you would do in a browser. So, if you want to know what class is applied to \n\n```\ncontainer.firstChild\n```\n\n you can just do it like this \n\n```\ncontainer.firstChild.className\n```\n\n. If you read more about \n\n```\nclassName\n```\n\n in MDN you'll see that it returns all the classes applied to your element separated by a space, that is: \n\n```\n
=> className === 'foo'\n
=> className === 'foo bar'\n```\n\n This might not be the best solution depending on your case. No worries, you can use another browser API, for example \n\n```\nclassList\n```\n\n. \n\n```\nexpect(container.firstChild.classList.contains('foo')).toBe(true)\n```\n\n That's it! No need to learn a new API that works only for tests. It's just as in the browser. If checking for a class is something you do often you can make the tests easier by adding jest-dom to your project. The test then becomes: \n\n```\nexpect(container.firstChild).toHaveClass('foo')\n```\n\n There are a bunch of other handy methods like \n\n```\ntoHaveStyle\n```\n\n that could help you. As a side note, react-testing-library is a proper JavaScript testing utility. It has many advantages over other libraries. I encourage you to join the spectrum forum if you're new to JavaScript testing. Share Improve this answer Follow edited Nov 20, 2018 at 14: 47 answered Nov 20, 2018 at 10: 56 Gio Polvara Gio Polvara 27. 4k 10 10 gold badges 69 69 silver badges 65 65 bronze badges 7 Hey! I see that you are using \n\n```\ntoBeTrue\n```\n\n but for some reason I get the \n\n```\nTypeError: expect(...).toBeTrue is not a function\n```\n\n. I run the latest Jest version. The \n\n```\ntoHaveClass\n```\n\n is working fine! Giesburts – Giesburts 11/20/2018 11: 22: 53 Commented Nov 20, 2018 at 11: 22 My bad it's \n\n```\ntoBe(true)\n```\n\n I fixed it. I use \n\n```\ntoHaveClass\n```\n\n though, way easier Gio Polvara – Gio Polvara 11/20/2018 14: 47: 37 Commented Nov 20, 2018 at 14: 47 @GiorgioPolvara-Gpx I still think it's a hacky way to do it when the library doesn't have support for getByClass method. Jaspreet Singh – Jaspreet Singh 07/16/2019 05: 26: 40 Commented Jul 16, 2019 at 5: 26 The library doesn't have a \n\n```\ngetByClass\n```\n\n method because it wants to push you to test as a user would. Users don't see classes. But if for some reason the rendered classes are something you want to test this is the way to do it. Gio Polvara – Gio Polvara 07/16/2019 08: 54: 14 Commented Jul 16, 2019 at 8: 54 1 You need to do it in two steps, one for \n\n```\nfoo\n```\n\n and the other for \n\n```\nbar\n```\n\n Gio Polvara – Gio Polvara 02/25/2020 14: 18: 25 Commented Feb 25, 2020 at 14: 18 | Show 2 more comments 108 The library gives access to normal DOM selectors, so we can also simply do this: \n\n```\nit('Renders with a className equal to the variant', () => {\n const { container } = render()\n expect(container.getElementsByClassName('default').length).toBe(1);\n});\n```\n\n Share Improve this answer Follow edited Mar 19, 2021 at 17: 25 Peter Mortensen 31. 6k 22 22 gold badges 110 110 silver badges 134 134 bronze badges answered Dec 3, 2020 at 1: 07 jbmilgrom 23. 7k 6 6 gold badges 29 29 silver badges 24 24 bronze badges 1 2 Don't forget to destructure container, or you'll get \n\n```\nProperty 'getElementsByClassName' does not exist on type 'RenderResult...\n```\n\n SeanMC – SeanMC 08/02/2023 15: 49: 41 Commented Aug 2, 2023 at 15: 49 Add a comment | 52 You need to understand the philosophy behind react-testing-library to understand what you can do and what you can't do with it; The goal behind react-testing-library is for the tests to avoid including implementation details of your components and rather focus on writing tests that give you the confidence for which they are intended. So querying element by classname is not aligned with the react-testing-library philosophy as it includes implementation details. The classname is actual the implementation detail of an element and is not something the end user will see, and it is subjected to change at anytime in the lifecycle of the element. So instead of searching an element by what the user cannot see, and something that can change at anytime, just try to search by using something that the user can see, such as text, label or something that will remain constant in the life cycle of the element like data-id. So to answer your question, it is not advised to test classname and hence you cannot do that with react-testing-library. Try with other test libraries such as Enzyme or react-dom test utils. Share Improve this answer Follow edited Jun 17, 2023 at 20: 08 Jasperan 4, 677 7 7 gold badges 30 30 silver badges 64 64 bronze badges answered May 28, 2019 at 5: 58 kasongoyo 1, 886 1 1 gold badge 17 17 silver badges 20 20 bronze badges 12 178 I've seen this answer given before here and from the authors of react-testing-library. I've never understood it. \"classNames\" are, by definition, things that users will see. They are at the very front lines of the user experience. It would be nice to know if a vital class helper has been applied to an element so that the element, for example, becomes visible. mrbinky3000 – mrbinky3000 11/26/2019 18: 10: 35 Commented Nov 26, 2019 at 18: 10 4 Adding to the above, some css libraries like semantic UI make the DOM more readable by looking at its CSS classes. So you have something like
or a
etc. Without querying by class its hard to assert when using sematic ui sethu – sethu 01/16/2020 20: 54: 15 Commented Jan 16, 2020 at 20: 54 4 @mrbinky3000 you can test the presence/absence of class in the element and that's very fine and well supported by RTL when used with jest-dom. What's ant-pattern is to locate the element by using className in tests. kasongoyo – kasongoyo 01/17/2020 09: 03: 04 Commented Jan 17, 2020 at 9: 03 23 Messing up the prod cod with data-testid is bigger no for me, than using the class attribute to browse in the rendered code. Not to mention that you don't really have a choice, if you want to check the render of a 3rd party code. Unless you want to mock out everything. Which about people are also making videos not to do. I think it's the case of great philosophy but not practical approach. bmolnar – bmolnar 12/24/2020 11: 27: 52 Commented Dec 24, 2020 at 11: 27 5 If your main concern is that your prod code has data-testid, those can always be stripped out during bundling. Ex: babel-plugin-jsx-remove-data-test-id Rui Marques – Rui Marques 09/24/2021 10: 44: 14 Commented Sep 24, 2021 at 10: 44 | Show 7 more comments 35 You can use testing-library/jest-dom custom matchers. The @testing-library/jest-dom library provides a set of custom jest matchers that you can use to extend jest. These will make your tests more declarative, clear to read and to maintain. https: //github. com/testing-library/jest-dom#tohaveclass \n\n```\nit('Renders with a className equal to the variant', () => {\n const { container } = render()\n expect(container.firstChild).toHaveClass('class-you-are-testing') \n})\n```\n\n This can be set up globally in a \n\n```\nsetupTest.js\n```\n\n file \n\n```\nimport '@testing-library/jest-dom/extend-expect';\nimport 'jest-axe/extend-expect';\n// etc\n```\n\n Share Improve this answer Follow answered Jun 12, 2020 at 11: 01 glenrothes 1, 743 1 1 gold badge 16 16 silver badges 18 18 bronze badges Add a comment | 18 You should use \n\n```\ntoHaveClass\n```\n\n from Jest. No need to add more logic. \n\n```\nit('Renders with a className equal to the variant', () => {\n const { container } = render()\n expect(container.firstChild).toHaveClass(add you className);\n // You can also use screen instead of container because container is not recommended as per Documentation \n expect(screen.getByRole('button')).toHaveClass(add you className)\n})\n```\n\n Share Improve this answer Follow edited Dec 27, 2023 at 16: 49 Cardinal System 3, 598 4 4 gold badges 28 28 silver badges 51 51 bronze badges answered Oct 13, 2021 at 20: 21 Yazan Najjar Yazan Najjar 2, 234 1 1 gold badge 18 18 silver badges 11 11 bronze badges 1 Basically the same as existing answers but with less context. ggorlen – ggorlen 05/20/2022 17: 21: 03 Commented May 20, 2022 at 17: 21 Add a comment | 7 You can use toHaveClass from jest DOM \n\n```\nit('renders textinput with optional classes', () => {\n const { container } = render()\n expect(container.children[1]).toHaveClass('class1')\n})\n```\n\n Don't forgot to destructure response like this \n\n```\n{container}\n```\n\n Because By default, React Testing Library will create a div and append that div to the \n\n```\ndocument.body\n```\n\n and this is where your React component will be rendered. If you provide your own \n\n```\nHTMLElement\n```\n\n container via this option, it will not be appended to the \n\n```\ndocument.body\n```\n\n automatically. Share Improve this answer Follow edited Sep 15, 2022 at 15: 20 Penny Liu 17. 9k 5 5 gold badges 88 88 silver badges 109 109 bronze badges answered Jun 13, 2022 at 11: 18 Shamaz saeed Shamaz saeed 446 4 4 silver badges 8 8 bronze badges Add a comment | 0 This a Real-World Storybook example with Jest and React Testing Library for testing \n\n```\n
\n```\n\n element, by its class name in this case, it's \n\n```\ntext-primary\n```\n\n. \n\n```\nEmpty.play = async ({ canvasElement, step }) => {\n const canvas = within(canvasElement)\n const paragraph = container.querySelector('p')\n await step('Should render Empty correctly', async () => {\n expect(paragraph).toBeInTheDocument()\n expect(paragraph.classList.contains('text-primary')).toBeFalsy()\n })\n await step('Should handle click', async () => {\n userEvent.click(paragraph)\n await waitFor(() => {\n expect(\n container.querySelector('p').classList.contains('text-primary')\n ).toBeTruthy()\n })\n })\n}\n```\n\n Share Improve this answer Follow answered Oct 5, 2023 at 19: 00 ahmnouira 3, 793 1 1 gold badge 36 36 silver badges 17 17 bronze badges 1 1 you should never use \"container\" queries. . . github. com/testing-library/eslint-plugin-testing-library/blob/… jebbie – jebbie 11/02/2023 09: 37: 20 Commented Nov 2, 2023 at 9: 37 Add a comment | 0 Well, nobody should use \n\n```\ncontainer\n```\n\n for all these cases, especially when you start working with the eslint plugins there are available for react-testing-library (more info: https: //kentcdodds. com/blog/common-mistakes-with-react-testing-library ) Ok, without container it's getting a bit hard to select basic elements. But there is a documentation about all ARIA roles here: https: //www. w3. org/TR/html-aria/#docconformance And so we stumble on this: https: //www. w3. org/TR/html-aria/#docconformance Yeah of course you SHOULD NOT use this - but for testing it's totally fine i would say. I mean, you should not use it in the real application, but this way, i can rewrite my test to make eslint happy again, and i think this should be the correct answer here: \n\n```\nconst body = screen.getByRole(\"generic\");\nexpect(body.classList.contains(\"bodyScrollLock-all\")).toBe(true);\nconst paragraph = screen.getByRole(\"paragraph\");\nexpect(paragraph.classList.contains(\"text-primary\")).toBe(true);\n```\n\n Share Improve this answer Follow answered Nov 2, 2023 at 9: 57 jebbie 1, 457 3 3 gold badges 18 18 silver badges 27 27 bronze badges Add a comment | -1 \n\n```\nit('check FAQ link is working or not', () => {\n const mockStore = configureStore({ reducer: Reducers });\n const { container } = render(\n \n \n \n \n \n \n ,\n );\n const faqLink = container.getElementsByClassName('breadcrumb-item active');\n expect(faqLink[0].textContent).toBe('FAQ /');\n });\n});\n```\n\n Share Improve this answer Follow edited Jun 16, 2023 at 13: 42 Super Kai - Kazuya Ito 1 answered Jun 15, 2023 at 13: 07 Abdul Mazood Abdul Mazood 1 3 1 As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center. Community – Community Bot 06/16/2023 01: 12: 47 Commented Jun 16, 2023 at 1: 12 You should add explanation. Super Kai - Kazuya Ito – Super Kai - Kazuya Ito 06/16/2023 13: 42: 30 Commented Jun 16, 2023 at 13: 42 Don't forget to destructure container, or you'll get \n\n```\nProperty 'getElementsByClassName' does not exist on type 'RenderResult...\n```\n\n SeanMC – SeanMC 08/02/2023 15: 50: 05 Commented Aug 2, 2023 at 15: 50 Add a comment | -2 \n\n```\n// Link.react.test.js\nimport React from 'react';\nimport ShallowRenderer from 'react-test-renderer/shallow';\nimport App from './../../src/App'\ndescribe('React', () => {\n it('className', () => {\n const renderer = new ShallowRenderer();\n renderer.render();\n const result = renderer.getRenderOutput();\n expect(result.props.className.split(' ').includes('welcome-framework')).toBe(true);\n });\n});\n```\n\n Share Improve this answer Follow answered May 20, 2021 at 7: 07 YinPeng. Wei YinPeng. Wei 598 4 4 silver badges 10 10 bronze badges Add a comment | Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript reactjs jestjs react-testing-library See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 4 testing-library-react: asserting class exists (for styling purposes) Related 14 React Enzyme Jest test component with className 0 Error while trying to test a JS Class using Jest 10 How to test class components in react 8 test method with jest and react-testing-library 1 How do I test method inside my class component? 9 Testing react components and getting elements by className 1 How do I test that my component has a specific className? 0 Checking for a class in React testing library 0 How do I mock document. getElementsByClassName() in jest and react-testing-library for the code-coverage? 0 Jest - Mock method of default class exported as named component of a package module Hot Network Questions Extra space after \\left…\\right workaround with \\vphantom in LaTeX Tiling a rectangle with heptominoes In search of 86-DOS ttsr. h and corresponding library Comparative law: Does a lease transfer all benefits at once or gradually? What kind of bug is this? Keep two entire Linux desktop systems in sync \"seen as X\" - sicut, ablative of means, other? What did Jesus eat in relationship to his Jewish culture and tradition? How to create a crossed rectangle as a custom vertex in TikZ-Feynman? If we have no free will, wherein lies the illusion? SAS hard drives are not accessible after removing RAID and using IT Mode What natural predators would prove the most dangerous for a village of tiny 5 inch people? How to write \"the positive sign is replaced by negative sign and negative sign by positive sign\"? Why is cinnamic acid nitrated at the ortho, para positions and not the meta position? Searching for an SF story that involved a politician who lost a chance at immortality because he was getting senile Birth control and the ambassador of the 22nd century Can I say \"inbound/outbound trips/journeys/visits to/from somewhere\"? How to prove that natural number less than is irrelevant? Looking for a short story collection, history of the universe starting with the big bang In what American magazine was Tolkien's \"Smith of Wootton Major\" first published? expr \"/foo\": \"/\" gives a syntax error A question on the paper \"Maximal unramified extensions of imaginary quadratic number fields of small conductors\" Appendix by a subset of the authors of the main paper How to sync Thunderbird emails, over two computers? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 3060,
- "timestamp": "2025-09-03 07:33:10"
- }
- },
- {
- "id": "1682a3bc3cb4",
- "url": "https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately",
- "title": "javascript - setState doesn't update the state immediately - Stack Overflow",
- "content": "setState doesn't update the state immediately [duplicate] Ask Question Asked 8 years, 8 months ago Modified 7 months ago Viewed 216k times 176 I would like to ask why my state is not changing when I do an \n\n```\nonClick\n```\n\n event. I've search a while ago that I need to bind the \n\n```\nonClick\n```\n\n function in constructor but still the state is not updating. Here's my code: \n\n```\nimport React from 'react';\nimport Grid from 'react-bootstrap/lib/Grid';\nimport Row from 'react-bootstrap/lib/Row';\nimport Col from 'react-bootstrap/lib/Col';\nimport BoardAddModal from 'components/board/BoardAddModal.jsx'; \nimport style from 'styles/boarditem.css';\nclass BoardAdd extends React.Component {\n constructor(props) {\n super(props); \n this.state = {\n boardAddModalShow: false\n }; \n this.openAddBoardModal = this.openAddBoardModal.bind(this);\n }\n openAddBoardModal() {\n this.setState({ boardAddModalShow: true }); // set boardAddModalShow to true\n /* After setting a new state it still returns a false value */\n console.log(this.state.boardAddModalShow); \n }\n render() { \n return (\n
\n \n \n );\n }\n}\nexport default BoardAdd\n```\n\n javascript node. js reactjs ecmascript-6 Share Improve this question Follow edited Feb 2, 2023 at 7: 15 Mayank Kumar Chaudhari 19. 1k 14 14 gold badges 73 73 silver badges 162 162 bronze badges asked Dec 22, 2016 at 8: 03 Sydney Loteria Sydney Loteria 10. 5k 21 21 gold badges 62 62 silver badges 73 73 bronze badges 2 10 The answer you've accepted on this question makes no sense. \n\n```\nsetState\n```\n\n doesn't return a promise. If it worked, it only worked because \n\n```\nawait\n```\n\n introduces one async \"tick\" into the function, and it happened that the state update got processed during that tick. It's not guaranteed. As this answer says, you need to use the completion callback (if you really need to do something after the state is updated, which is unusual; normally, you just want to re-render, which hapens automatically). T. J. Crowder – T. J. Crowder 08/19/2019 09: 10: 54 Commented Aug 19, 2019 at 9: 10 3 It would be good if you un-accepted the currently accepteded answer or accepted a correct one, because this could then be used as a duplicate for many other questions. Having an incorrect answer at the top is misleading. Guy Incognito – Guy Incognito 05/28/2020 05: 09: 48 Commented May 28, 2020 at 5: 09 Add a comment | 15 Answers 15 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 220 Your state needs some time to mutate, and since \n\n```\nconsole.log(this.state.boardAddModalShow)\n```\n\n executes before the state mutates, you get the previous value as output. So you need to write the console in the callback to the \n\n```\nsetState\n```\n\n function \n\n```\nopenAddBoardModal() {\n this.setState({ boardAddModalShow: true }, function () {\n console.log(this.state.boardAddModalShow);\n });\n}\n```\n\n \n\n```\nsetState\n```\n\n is asynchronous. It means you can’t call it on one line and assume the state has changed on the next. According to React docs \n\n```\nsetState()\n```\n\n does not immediately mutate \n\n```\nthis.state\n```\n\n but creates a pending state transition. Accessing \n\n```\nthis.state\n```\n\n after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. Why would they make \n\n```\nsetState\n```\n\n async This is because \n\n```\nsetState\n```\n\n alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive. Thus the \n\n```\nsetState\n```\n\n calls are asynchronous as well as batched for better UI experience and performance. Share Improve this answer Follow edited Sep 17, 2024 at 21: 58 omers 347 1 1 gold badge 5 5 silver badges 14 14 bronze badges answered Dec 22, 2016 at 8: 06 Shubham Khatri Shubham Khatri 283k 58 58 gold badges 431 431 silver badges 411 411 bronze badges 9 Until now it is an great idea, BUT what if we can't use console. log because u're using eslint rules? maudev – maudev 01/25/2019 06: 16: 31 Commented Jan 25, 2019 at 6: 16 2 @maudev, eslint rules stop you to have console. logs so that they don't end up in production, but the above example is purely for debugging. and console. log and be replaced with an action which takes into account the updated state Shubham Khatri – Shubham Khatri 01/25/2019 06: 44: 24 Commented Jan 25, 2019 at 6: 44 1 What if the callback does not work as you said? mine does not! Ghasem – Ghasem 08/29/2019 06: 31: 31 Commented Aug 29, 2019 at 6: 31 1 @VaibhavSidapara Check this post. Let me know if it helps Shubham Khatri – Shubham Khatri 04/20/2021 12: 38: 29 Commented Apr 20, 2021 at 12: 38 1 @ShubhamKhatri thanks, I solved it yesterday. I used the same useEffect hook. Vaibhav Sidapara – Vaibhav Sidapara 04/21/2021 16: 28: 52 Commented Apr 21, 2021 at 16: 28 | Show 4 more comments 62 Fortunately \n\n```\nsetState()\n```\n\n takes a callback. And this is where we get updated state. Consider this example. \n\n```\nthis.setState({ name: \"myname\" }, () => { \n //callback\n console.log(this.state.name) // myname\n });\n```\n\n So When callback fires, this. state will be the updated state. You can get \n\n```\nmutated/updated\n```\n\n data in callback. Share Improve this answer Follow edited Jan 24 at 10: 11 answered Jul 9, 2018 at 11: 16 Mustkeem K Mustkeem K 8, 876 2 2 gold badges 34 34 silver badges 45 45 bronze badges 4 1 You can also use this callback to pass any function, \n\n```\ninitMap()\n```\n\n, for instance Dende – Dende 12/21/2018 13: 01: 21 Commented Dec 21, 2018 at 13: 01 1 Way to go! Finally solved my problem. Thanks a lot. Ahmet Halilović – Ahmet Halilović 08/13/2020 20: 16: 22 Commented Aug 13, 2020 at 20: 16 1 this gives a warning in ReactJS functional component Gopal Mishra – Gopal Mishra 10/13/2021 08: 03: 45 Commented Oct 13, 2021 at 8: 03 don't depend on state and it will update the state and you will get update value through variable. let categories = [. . . selectedCategory, value] setSelectedCategory(categories); setInputValue(categories) using this piece of code you will get update value becuase you are not dependent on the state. santu prajapati – santu prajapati 02/21/2023 09: 20: 36 Commented Feb 21, 2023 at 9: 20 Add a comment | 23 For anyone trying to do this with hooks, you need \n\n```\nuseEffect\n```\n\n. \n\n```\nfunction App() {\n const [x, setX] = useState(5)\n const [y, setY] = useState(15) \n console.log(\"Element is rendered:\", x, y)\n // setting y does not trigger the effect\n // the second argument is an array of dependencies\n useEffect(() => console.log(\"re-render because x changed:\", x), [x])\n function handleXClick() {\n console.log(\"x before setting:\", x)\n setX(10)\n console.log(\"x in *line* after setting:\", x)\n }\n return <>\n
x is {x}.
\n \n
y is {y}.
\n \n >\n}\n```\n\n Output: \n\n```\nElement is rendered: 5 15\nre-render because x changed: 5\n(press x button)\nx before setting: 5\nx in *line* after setting: 5\nElement is rendered: 10 15\nre-render because x changed: 10\n(press y button)\nElement is rendered: 10 20\n```\n\n Live version Share Improve this answer Follow edited Feb 1, 2022 at 23: 43 answered Jul 21, 2020 at 20: 20 Luke Miles Luke Miles 1, 200 11 11 silver badges 23 23 bronze badges Add a comment | 17 Since setSatate is a asynchronous function so you need to console the state as a callback like this. \n\n```\nopenAddBoardModal(){\n this.setState({ boardAddModalShow: true }, () => {\n console.log(this.state.boardAddModalShow)\n });\n}\n```\n\n Share Improve this answer Follow edited Jul 27, 2018 at 16: 48 yanckst 446 4 4 silver badges 17 17 bronze badges answered Jul 20, 2018 at 13: 20 Adnan 1, 707 13 13 silver badges 19 19 bronze badges Add a comment | 9 \n\n```\nsetState()\n```\n\n does not always immediately update the component. It may batch or defer the update until later. This makes reading this. state right after calling \n\n```\nsetState()\n```\n\n a potential pitfall. Instead, use \n\n```\ncomponentDidUpdate\n```\n\n or a \n\n```\nsetState\n```\n\n callback ( \n\n```\nsetState(updater, callback)\n```\n\n ), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below. \n\n```\nsetState()\n```\n\n will always lead to a re-render unless \n\n```\nshouldComponentUpdate()\n```\n\n returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in \n\n```\nshouldComponentUpdate()\n```\n\n, calling \n\n```\nsetState()\n```\n\n only when the new state differs from the previous state will avoid unnecessary re-renders. The first argument is an updater function with the signature: \n\n```\n(state, props) => stateChange\n```\n\n \n\n```\nstate\n```\n\n is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props. For instance, suppose we wanted to increment a value in state by props. step: \n\n```\nthis.setState((state, props) => {\n return {counter: state.counter + props.step};\n});\n```\n\n Share Improve this answer Follow edited Nov 26, 2018 at 18: 53 groenhen 3, 017 25 25 gold badges 51 51 silver badges 69 69 bronze badges answered Nov 26, 2018 at 18: 09 Aman Seth Aman Seth 305 2 2 silver badges 9 9 bronze badges Add a comment | 6 Think of \n\n```\nsetState()\n```\n\n as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately. Check this for more information. In your case you have sent a request to update the state. It takes time for React to respond. If you try to immediately \n\n```\nconsole.log\n```\n\n the state, you will get the old value. Share Improve this answer Follow edited Feb 14, 2021 at 7: 41 ggorlen 59k 8 8 gold badges 118 118 silver badges 170 170 bronze badges answered Dec 13, 2020 at 9: 08 M Fuat M Fuat 1, 440 3 3 gold badges 16 16 silver badges 25 25 bronze badges Add a comment | 3 This callback is really messy. Just use async await instead: \n\n```\nasync openAddBoardModal(){\n await this.setState({ boardAddModalShow: true });\n console.log(this.state.boardAddModalShow);\n}\n```\n\n Share Improve this answer Follow edited Dec 2, 2019 at 9: 04 Martijn Pieters 1. 1m 324 324 gold badges 4. 2k 4. 2k silver badges 3. 4k 3. 4k bronze badges answered Sep 7, 2018 at 15: 19 Spock 2, 761 1 1 gold badge 31 31 silver badges 29 29 bronze badges 8 61 That makes no sense. React's \n\n```\nsetState\n```\n\n doesn't return a promise. T. J. Crowder – T. J. Crowder 08/19/2019 09: 06: 27 Commented Aug 19, 2019 at 9: 06 25 @T. J. Crowder is right. \n\n```\nsetState\n```\n\n doesn't return a promise, so it should NOT be awaited. That said, I think I can see why this is working for some people, because await puts the inner workings of setState on the call stack ahead of the rest of the function, so it gets processed first, and thus seems like the state has been set. If setState had or implements any new asynchronous calls, this answer would fail. To implement this function properly, you can use this: \n\n```\nawait new Promise(resolve => this.setState({ boardAddModalShow: true }, () => resolve()))\n```\n\n Mike Richards – Mike Richards 10/03/2019 17: 57: 19 Commented Oct 3, 2019 at 17: 57 How the hell \n\n```\nasync this.setState({})\n```\n\n solved my issue? We had working code, some more development has been done but nothing changed that part of the app. Only one of two objects in setState was getting updated, making it async returned functionality back and now both objects are correctly updating. I have freaking no idea what the hell was wrong. Ondřej Ševčík – Ondřej Ševčík 09/04/2020 19: 48: 03 Commented Sep 4, 2020 at 19: 48 I found this question, but this solution didn't work for me, I didn't solve my problem yet but I found a good read here: ozmoroz. com/2018/11/why-my-setstate-doesnt-work carmolim – carmolim 10/02/2020 02: 24: 37 Commented Oct 2, 2020 at 2: 24 1 @OndřejŠevčík most likely a race-condition makes it looks like it works, but it'll possibly break again someday. Emile Bergeron – Emile Bergeron 03/10/2021 20: 13: 15 Commented Mar 10, 2021 at 20: 13 | Show 3 more comments 3 If you want to track the state is updating or not then the another way of doing the same thing is \n\n```\n_stateUpdated(){\n console.log(this.state. boardAddModalShow);\n}\nopenAddBoardModal(){\n this.setState(\n {boardAddModalShow: true}, \n this._stateUpdated.bind(this)\n );\n}\n```\n\n This way you can call the method \"_stateUpdated\" every time you try to update the state for debugging. Share Improve this answer Follow answered Jul 28, 2018 at 21: 20 Ravin Gupta Ravin Gupta 853 8 8 silver badges 13 13 bronze badges Add a comment | 3 Although there are many good answers, if someone lands on this page searching for alternative to \n\n```\nuseState\n```\n\n for implementing UI components like Navigation drawers which should be opened or closed based on user input, this answer would be helpful. Though \n\n```\nuseState\n```\n\n seems handy approach, the state is not set immediately and thus, your website or app looks laggy. . . And if your page is large enough, react is going to take long time to compute what all should be updated upon state change. . . My suggestion is to use refs and directly manipulate the DOM when you want UI to change immediately in response to user action. Using state for this purspose is really a bad idea in case of react. Share Improve this answer Follow answered Mar 23, 2021 at 17: 09 Mayank Kumar Chaudhari Mayank Kumar Chaudhari 19. 1k 14 14 gold badges 73 73 silver badges 162 162 bronze badges Add a comment | 3 The above solutions don't work for useState hooks. One can use the below code \n\n```\nsetState((prevState) => {\n console.log(boardAddModalShow)\n // call functions\n // fetch state using prevState and update\n return { ...prevState, boardAddModalShow: true }\n });\n```\n\n Share Improve this answer Follow answered Oct 24, 2021 at 18: 03 NevetsKuro 1, 014 9 9 silver badges 19 19 bronze badges 1 2 This makes no sense to me. I cannot translate it to my app. All I want to do is \n\n```\nsetMyVariable(false)\n```\n\n hook variable immediately. Why is this so hard? velkoon – velkoon 11/02/2022 04: 34: 30 Commented Nov 2, 2022 at 4: 34 Add a comment | 2 \n\n```\nsetState()\n```\n\n is asynchronous. The best way to verify if the state is updating would be in the \n\n```\ncomponentDidUpdate()\n```\n\n and not to put a \n\n```\nconsole.log(this.state.boardAddModalShow)\n```\n\n after \n\n```\nthis.setState({ boardAddModalShow: true })\n```\n\n. according to React Docs Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately Share Improve this answer Follow answered Mar 3, 2019 at 7: 55 stuli 57 10 10 bronze badges Add a comment | 2 According to React Docs React does not guarantee that the state changes are applied immediately. This makes reading this. state right after calling setState() a potential \n\n```\npitfall\n```\n\n and can potentially return the \n\n```\nexisting\n```\n\n value due to \n\n```\nasync\n```\n\n nature. Instead, use \n\n```\ncomponentDidUpdate\n```\n\n or a \n\n```\nsetState\n```\n\n callback that is executed right after setState operation is successful. Generally we recommend using \n\n```\ncomponentDidUpdate()\n```\n\n for such logic instead. Example: \n\n```\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport \"./styles.css\";\nclass App extends React.Component {\n constructor() {\n super();\n this.state = {\n counter: 1\n };\n }\n componentDidUpdate() {\n console.log(\"componentDidUpdate fired\");\n console.log(\"STATE\", this.state);\n }\n updateState = () => {\n this.setState(\n (state, props) => {\n return { counter: state.counter + 1 };\n });\n };\n render() {\n return (\n
\n
Hello CodeSandbox
\n
Start editing to see some magic happen!
\n \n
\n );\n }\n}\nconst rootElement = document.getElementById(\"root\");\nReactDOM.render(, rootElement);\n```\n\n Share Improve this answer Follow answered May 18, 2019 at 7: 55 khizerrehandev 1, 577 17 17 silver badges 15 15 bronze badges Add a comment | 0 \n\n```\nthis.setState({\n isMonthFee: !this.state.isMonthFee,\n }, () => {\n console.log(this.state.isMonthFee);\n })\n```\n\n Share Improve this answer Follow answered Apr 12, 2019 at 6: 42 Atchutha rama reddy Karri Atchutha rama reddy Karri 1, 569 15 15 silver badges 16 16 bronze badges 1 4 This is exactly what the most upvoted answer explains, but without any explanation and 3 years late. Please do not post duplicate answers unless you have something relevant to add to it. Emile Bergeron – Emile Bergeron 05/23/2020 02: 37: 47 Commented May 23, 2020 at 2: 37 Add a comment | 0 when i was running the code and checking my output at console it showing the that it is undefined. After i search around and find something that worked for me. \n\n```\ncomponentDidUpdate(){}\n```\n\n I added this method in my code after constructor(). check out the life cycle of react native workflow. https: //images. app. goo. gl/BVRAi4ea2P4LchqJ8 Share Improve this answer Follow answered Oct 24, 2019 at 9: 25 community wiki Pravin Ghorle Add a comment | -1 Yes because setState is an asynchronous function. The best way to set state right after you write set state is by using Object. assign like this: For eg you want to set a property isValid to true, do it like this Object. assign(this. state, { isValid: true }) You can access updated state just after writing this line. Share Improve this answer Follow answered Aug 28, 2019 at 10: 20 Dipanshu Sharma Dipanshu Sharma 53 6 6 bronze badges 1 1 Don't do this, it mutates the current state, which is an anti-pattern. Emile Bergeron – Emile Bergeron 05/18/2020 20: 24: 19 Commented May 18, 2020 at 20: 24 Add a comment | Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript node. js reactjs ecmascript-6 See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 905 The useState set method is not reflecting a change immediately 432 Why does calling react setState method not mutate the state immediately? 7 How to access updated state value in same function that used to set state value 6 setState not working in setInterval 2 React. js setState not working 2 ReactJS: setState using if else 1 React state undefined after setState? 2 setState doesn't update state in react 2 setState called in ComponentDidMount is not updating the state? 1 Cannot access state from ComponentDidMount() See more linked questions Related 6387 What is the difference between \"let\" and \"var\"? 8537 What does \"use strict\" do in JavaScript, and what is the reasoning behind it? 6740 How do I return the response from an asynchronous call? 5572 What's the difference between tilde(~) and caret(^) in package. json? 2922 How can I update each dependency in package. json to the latest version? 5391 How do I make the first letter of a string uppercase in JavaScript? 5157 What is the most efficient way to deep clone an object in JavaScript? 3154 What is the --save option for npm install? 4214 What does the! ! (double exclamation mark) operator do in JavaScript? 4343 How do I copy to the clipboard in JavaScript? Hot Network Questions Does Jesus' statement in Luke 21: 19 indicate that Stephen acted without the wisdom he should have received? Does Japanese have a gender-neutral third person pronoun? french interferes with iso time display How does one get more oxyfern? Knowledge is free, but time costs money? When to use \"tun würde*\" vs. \"täte*\" as the subjunctive II of \"tun\" Randomly losing network connectivity after reboot. . . Is it a hardware issue? Would this weapon be good for catching melee weapons? Is a condition termed a \"disease\" only when it has a known cause? How to approach untraceable citation Can I say \"inbound/outbound trips/journeys/visits to/from somewhere\"? Add Y to X to get a palindrome Would it be reasonable for a theist to claim that an atheist cannot appeal to any convention or apparatus of logic if there is no foundational agent? How to merge two tables with a different amount of columns in one table? Does the age limit for U. S. presidents apply at the the time of election or swearing in? Meaning of '#' suffix on SQL Server columns Volume-preserving fluid flows are incompressible. What about surface-area preserving flows? What was the first game where your guide/quest giver turned out to be a key antagonist/villain? Comparative law: Does a lease transfer all benefits at once or gradually? Do C++20 attributes [[likely]] and [[unlikely]] have anything to do with \"Speculative Execution\"? When would a court impose a harsher sentence than the prosecutor requests? 90-00s TV show. Colony established on a habitable planet. Colony is surrounded by a large wall. Expedition outside the wall encounter exiled group Did the Apollo Command Module launch with the docking probe already in place? Naming of parent keys and their modes more hot questions lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 3633,
- "timestamp": "2025-09-03 07:33:11"
- }
- },
- {
- "id": "9a16a20b0be1",
- "url": "https://stackoverflow.com/questions/36415904/is-there-a-way-to-use-map-on-an-array-in-reverse-order-with-javascript",
- "title": "Is there a way to use map() on an array in reverse order with javascript? - Stack Overflow",
- "content": "Is there a way to use map() on an array in reverse order with javascript? Ask Question Asked 9 years, 5 months ago Modified 2 years, 1 month ago Viewed 214k times 205 I want to use the \n\n```\nmap()\n```\n\n function on a JavaScript array, but I would like it to operate in reverse order. The reason is, I'm rendering stacked React components in a Meteor project and would like the top-level element to render first while the rest load the images below. \n\n```\nvar myArray = ['a', 'b', 'c', 'd', 'e'];\nmyArray.map(function (el, index, coll) {\n console.log(el + \" \")\n});\n```\n\n prints out \n\n```\na b c d e\n```\n\n, but I wish there was a mapReverse() that printed \n\n```\ne d c b a\n```\n\n. How can I do it? javascript arrays Share Improve this question Follow edited Jul 11, 2023 at 15: 06 Peter Mortensen 31. 6k 22 22 gold badges 110 110 silver badges 134 134 bronze badges asked Apr 5, 2016 at 2: 06 Robin Newhouse Robin Newhouse 2, 418 2 2 gold badges 21 21 silver badges 17 17 bronze badges 4 4 Why don't you \n\n```\nreverse\n```\n\n the array? John – John 04/05/2016 02: 08: 22 Commented Apr 5, 2016 at 2: 08 2 To order the elements I set the z-index by the array index. I suppose I could set the z-index to be negative. Robin Newhouse – Robin Newhouse 04/05/2016 02: 11: 01 Commented Apr 5, 2016 at 2: 11 1 On a side note, are you actually using the array that \n\n```\nmap\n```\n\n returns? Otherwise, you ought to consider \n\n```\nforEach\n```\n\n. canon – canon 04/05/2016 02: 16: 04 Commented Apr 5, 2016 at 2: 16 2 You could access the reverse element within the map callback: \n\n```\nconsole.log(coll[coll.length - index - 1] + \" \")\n```\n\n le_m – le_m 05/05/2017 20: 49: 52 Commented May 5, 2017 at 20: 49 Add a comment | 16 Answers 16 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 356 If you don't want to reverse the original array, you can make a shallow copy of it then map of the reversed array, \n\n```\nmyArray.slice(0).reverse().map(function(...\n```\n\n Update: \n\n```\nmyArray.toReversed().map(()=>{...});\n```\n\n The state of JavaScript has advanced since my original answer. Array. toReversed() now has support in most environments, and is a more modern and clean way to express mapping over the original array backwards, without changing the original. Share Improve this answer Follow edited Jul 11, 2023 at 14: 56 Peter Mortensen 31. 6k 22 22 gold badges 110 110 silver badges 134 134 bronze badges answered Apr 5, 2016 at 2: 13 AdamCooper86 4, 227 1 1 gold badge 15 15 silver badges 19 19 bronze badges 5 3 I ended up just using the negative index to specify the z-index, but in the way I framed the question this is the most correct. Robin Newhouse – Robin Newhouse 04/05/2016 02: 25: 46 Commented Apr 5, 2016 at 2: 25 9 Why do we need. slice(0)? Why not myArray. reverse() instead of myArray. slice(0). reverse()? Looks like the answer for my comment is here: stackoverflow. com/questions/5024085/… Haradzieniec – Haradzieniec 06/20/2017 09: 03: 34 Commented Jun 20, 2017 at 9: 03 Haradzieniec - It goes with the particulars for how the original question was framed, in that the original ordering was needed to set a Z-index css property, but printed in reverse. AdamCooper86 – AdamCooper86 06/21/2017 18: 46: 54 Commented Jun 21, 2017 at 18: 46 26 @FahdLihidheb \n\n```\nreverse()\n```\n\n DOES modify the original array. Ferus – Ferus 04/16/2020 10: 13: 28 Commented Apr 16, 2020 at 10: 13 2 Sure \n\n```\n.reverse()\n```\n\n DOES modify its input, but it's almost always possible to do the mapping FIRST, and only then reverse, because \n\n```\n.map()\n```\n\n creates a fresh array that's not shared anywhere else when reversing: \n\n```\nmyArray.map(...).reverse()\n```\n\n unless the mapping function looks ahead or backwards in the third argument (array) in which case the indexing needs to change Robert Monfera – Robert Monfera 10/09/2021 20: 31: 29 Commented Oct 9, 2021 at 20: 31 Add a comment | 62 Use math on the \n\n```\nindex\n```\n\n provided to the mapping function in order to access elements in reverse order, rather than using the provided \n\n```\nval\n```\n\n: \n\n```\nmyArray.map((val, index) => myArray[myArray.length - 1 - index]);\n```\n\n This is O(n) and does not mutate nor copy the input array. The third parameter to the mapping function is the underlying collection, so that can also avoid the need to refer to it via a closure: \n\n```\nmyArray.map((val, index, array) => array[array.length - 1 - index]);\n```\n\n Share Improve this answer Follow edited Jul 11, 2023 at 15: 08 Karl Knechtel 61. 2k 14 14 gold badges 131 131 silver badges 191 191 bronze badges answered Oct 15, 2018 at 20: 38 tyborg 663 5 5 silver badges 8 8 bronze badges 2 You could write \n\n```\n_val\n```\n\n instead of \n\n```\nval\n```\n\n to denote it's not used. @Paul You need the full syntax \n\n```\n(first, second, third) => ...\n```\n\n as both the \n\n```\nindex\n```\n\n (second) and the base \n\n```\narray\n```\n\n / \n\n```\nmyArray\n```\n\n (third) are used here. Cadoiz – Cadoiz 05/22/2023 13: 15: 53 Commented May 22, 2023 at 13: 15 Such a great answer, just returned here. Note to myself: \n\n```\n[...myArray]\n```\n\n or \n\n```\n.slice(0)\n```\n\n (with or without the \n\n```\n0\n```\n\n ) make a shallow copy. You could write something like \n\n```\nconst el = array[array.length - 1 - index]\n```\n\n to directly reuse the element like OP does inside his loop in the question. Cadoiz – Cadoiz 07/06/2023 10: 26: 23 Commented Jul 6, 2023 at 10: 26 Add a comment | 27 You can use \n\n```\nArray.prototype.reduceRight()\n```\n\n \n\n```\nvar myArray = [\"a\", \"b\", \"c\", \"d\", \"e\"];\r\nvar res = myArray.reduceRight(function (arr, last, index, coll) {\r\n console.log(last, index);\r\n return (arr = arr.concat(last))\r\n}, []);\r\nconsole.log(res, myArray)\n```\n\n Share Improve this answer Follow answered Apr 5, 2016 at 2: 23 guest271314 1 1 noice (if you are looking to perform a reduce anyways) - MDN: The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value. TamusJRoyce – TamusJRoyce 09/09/2020 21: 08: 36 Commented Sep 9, 2020 at 21: 08 Add a comment | 23 With Named callback function \n\n```\nconst items = [1, 2, 3]; \nconst reversedItems = items.map(function iterateItems(item) {\n return item; // or any logic you want to perform\n}).reverse();\n```\n\n Shorthand (without named callback function) - Arrow Syntax, ES6 \n\n```\nconst items = [1, 2, 3];\nconst reversedItems = items.map(item => item).reverse();\n```\n\n Here is the result Share Improve this answer Follow answered Mar 16, 2019 at 19: 49 Harry 981 2 2 gold badges 12 12 silver badges 18 18 bronze badges 3 1 map is being used as a shallow copy TamusJRoyce – TamusJRoyce 09/09/2020 21: 03: 08 Commented Sep 9, 2020 at 21: 03 This uses \n\n```\nitems.map\n```\n\n as a shallow copy. \n\n```\n[...items]\n```\n\n or \n\n```\nitems.slice(0)\n```\n\n (with or without the \n\n```\n0\n```\n\n ) would do the same. Cadoiz – Cadoiz 07/06/2023 10: 20: 29 Commented Jul 6, 2023 at 10: 20 This reverses the results, rather than the order of iteration. Karl Knechtel – Karl Knechtel 07/11/2023 15: 14: 44 Commented Jul 11, 2023 at 15: 14 Add a comment | 13 Another solution could be: \n\n```\nconst reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);\n```\n\n You basically work with the array indexes Share Improve this answer Follow answered Sep 14, 2018 at 1: 30 Matteo 2, 692 2 2 gold badges 36 36 silver badges 48 48 bronze badges 3 2 This seems like a strange way to go, but the reduceRight approach is also odd if you're wanting access to the index in addition to the element, don't really want to do a reduce, etc. In my case, this was the cleanest solution. RealHandy – RealHandy 10/10/2018 21: 42: 40 Commented Oct 10, 2018 at 21: 42 2 If you need to do further work inside the map, using arr[. . . ] doesn't require a second copy or manipulating the original array. Forgot about the 3rd parameter. What I was looking for! TamusJRoyce – TamusJRoyce 09/09/2020 21: 05: 56 Commented Sep 9, 2020 at 21: 05 This is actually duplicated by this higher-voted answer Cadoiz – Cadoiz 07/06/2023 10: 24: 03 Commented Jul 6, 2023 at 10: 24 Add a comment | 13 You just need to add \n\n```\n.slice(0).reverse()\n```\n\n before \n\n```\n.map()\n```\n\n \n\n```\nstudents.slice(0).reverse().map(e => e.id)\n```\n\n Share Improve this answer Follow edited Nov 15, 2021 at 8: 14 answered Jul 4, 2021 at 5: 55 Ali Raza Ali Raza 1, 083 14 14 silver badges 20 20 bronze badges 1 This uses \n\n```\n.slice(0)\n```\n\n as a shallow copy. It doesn't matter, with or without the \n\n```\n0\n```\n\n. Actually, the last \n\n```\n.map\n```\n\n makes yet another copy without the need for it. Cadoiz – Cadoiz 07/06/2023 10: 22: 02 Commented Jul 6, 2023 at 10: 22 Add a comment | 7 I prefer to write the mapReverse function once, then use it. Also this doesn't need to copy the array. \n\n```\nfunction mapReverse(array, fn) {\n return array.reduceRight(function (result, el) {\n result.push(fn(el));\n return result;\n }, []);\n}\nconsole.log(mapReverse([1, 2, 3], function (i) { return i; }))\n// [ 3, 2, 1 ]\nconsole.log(mapReverse([1, 2, 3], function (i) { return i * 2; }))\n// [ 6, 4, 2 ]\n```\n\n Share Improve this answer Follow answered Feb 18, 2018 at 8: 20 edi9999 20. 7k 15 15 gold badges 98 98 silver badges 136 136 bronze badges Add a comment | 3 I think put the \n\n```\nreverse()\n```\n\n key after \n\n```\nmap\n```\n\n is working. \n\n```\ntbl_products\n .map((products) => (\n
\n ))\n .reverse();\n```\n\n In my case, it is working Share Improve this answer Follow answered Mar 10, 2021 at 7: 11 Neeraj Tangariya Neeraj Tangariya 1, 417 1 1 gold badge 24 24 silver badges 30 30 bronze badges Add a comment | 3 You can do \n\n```\nmyArray.reverse()\n```\n\n first. \n\n```\nvar myArray = ['a', 'b', 'c', 'd', 'e'];\nmyArray.reverse().map(function (el, index, coll) {\n console.log(el + \" \")\n});\n```\n\n Share Improve this answer Follow edited May 22, 2023 at 18: 42 Cadoiz 1, 684 2 2 gold badges 25 25 silver badges 36 36 bronze badges answered Apr 5, 2016 at 2: 11 dannielum 356 1 1 silver badge 11 11 bronze badges 3 That would be my solution in general, but in the setup I'm using the top card is placed with the last index. I guess just some better indexing could solve the problem. Robin Newhouse – Robin Newhouse 04/05/2016 02: 14: 58 Commented Apr 5, 2016 at 2: 14 20 Just as a note, this will reverse the original array in place, meaning it will alter the order of the array destructively. AdamCooper86 – AdamCooper86 04/05/2016 02: 15: 25 Commented Apr 5, 2016 at 2: 15 I started googling after this did not work for me at all. Turns out react in dev mode renders twice, so it was reversing the array twice and ui showed everything in the original order: ) unkulunkulu – unkulunkulu 05/22/2023 22: 30: 49 Commented May 22, 2023 at 22: 30 Add a comment | 2 Here is my TypeScript solution that is both O(n) and more efficient than the other solutions by preventing a run through the array twice: \n\n```\nfunction reverseMap(arg: T[], fn: (a: T) => O) {\n return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))\n}\n```\n\n In JavaScript: \n\n```\nconst reverseMap = (arg, fn) => arg.map((_, i, arr) => fn(arr[arr.length - 1 - i]))\n// Or \nfunction reverseMap(arg, fn) {\n return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))\n}\n```\n\n Share Improve this answer Follow answered Aug 16, 2020 at 1: 44 Jack 1, 116 1 1 gold badge 14 14 silver badges 37 37 bronze badges Add a comment | 2 First, you should make a shallow copy of the array, and then use that function on the copy. \n\n```\n[...myArray].reverse().map(function(...\n```\n\n Share Improve this answer Follow edited May 23, 2023 at 14: 50 Cadoiz 1, 684 2 2 gold badges 25 25 silver badges 36 36 bronze badges answered Jun 9, 2022 at 10: 57 Nazanin 21 1 1 bronze badge Add a comment | 1 \n\n```\nfunction mapRevers(reverse) {\n let reversed = reverse.map( (num,index,reverse) => reverse[(reverse.length-1)-index] );\n return reversed;\n}\nconsole.log(mapRevers(myArray));\n```\n\n I You pass the array to map Revers and in the function you return the reversed array. In the map cb you simply take the values with the index counting from 10 (length) down to 1 from the passed array Share Improve this answer Follow edited Oct 18, 2020 at 9: 48 answered Oct 18, 2020 at 7: 22 Mathias Eckrodt Mathias Eckrodt 41 1 1 silver badge 9 9 bronze badges 1 A written explanation as to what this code is doing may be helpful. Pro Q – Pro Q 10/18/2020 08: 26: 41 Commented Oct 18, 2020 at 8: 26 Add a comment | 1 \n\n```\nvar myArray = ['a', 'b', 'c', 'd', 'e'];\nvar reverseArray = myArray.reverse()\nreverseArray.map(function (el, index, coll) {\n console.log(el + \" \")\n});\n```\n\n Share Improve this answer Follow answered Mar 10, 2021 at 7: 31 Iron Man Iron Man 65 3 3 bronze badges 1 3 \n\n```\nreverse\n```\n\n will also reverse the \n\n```\nmyArray\n```\n\n in-place. As the (unexpected) side effect, your \n\n```\nmyArray\n```\n\n get reversed after executing these codes. The same problem similar to this answer tsh – tsh 05/13/2021 06: 17: 04 Commented May 13, 2021 at 6: 17 Add a comment | 0 If you are using an immutable array from let's say a redux reducer state, you can apply \n\n```\n.reverse()\n```\n\n by first making a copy like this: \n\n```\nconst reversedArray = [...myArray].reverse();\n//where myArray is a state variable\n//later in code\nreversedArray.map((item, i)=>doStuffWith(item))\n```\n\n Share Improve this answer Follow answered Mar 7, 2022 at 14: 43 Erbaz Kamran Erbaz Kamran 78 1 1 silver badge 7 7 bronze badges Add a comment | 0 Add reverse() into your code snippet: \n\n```\nYourData.reverse().map(...)\n```\n\n Be aware that this will mutate the original array, which can be an issue. Share Improve this answer Follow edited Jun 20, 2023 at 13: 46 TylerH 21. 2k 82 82 gold badges 81 81 silver badges 119 119 bronze badges answered Sep 13, 2022 at 16: 14 Joseph Fatoye Joseph Fatoye 9 1 1 bronze badge 2 1 This repeats several answers already. New answers should contain novel solutions, not repeat existing ones. TylerH – TylerH 06/20/2023 13: 48: 19 Commented Jun 20, 2023 at 13: 48 There is this meta-post on editing the answer Cadoiz – Cadoiz 07/11/2023 06: 46: 22 Commented Jul 11, 2023 at 6: 46 Add a comment | -2 An old question but for new viewers, this is the best way to reverse array using map \n\n```\nvar myArray = ['a', 'b', 'c', 'd', 'e'];\n[...myArray].map(() => myArray.pop());\n```\n\n Share Improve this answer Follow answered Mar 20, 2020 at 14: 37 Duong Thanh Hop Duong Thanh Hop 9 2 this modifies the original array TamusJRoyce – TamusJRoyce 09/09/2020 20: 57: 29 Commented Sep 9, 2020 at 20: 57 maybe you meant: \n\n```\n[...myArray].map((_, _, arr) => arr.pop());\n```\n\n? Matteo – Matteo 09/10/2020 00: 35: 47 Commented Sep 10, 2020 at 0: 35 Add a comment | Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript arrays See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Visit chat Linked -2 How can i map an array starting from the end of the array to the beginning? 79 What's the point of. slice(0) here? -1 gApps script: deleteRow() does not work Related 12210 How can I remove a specific item from an array in JavaScript? 8537 What does \"use strict\" do in JavaScript, and what is the reasoning behind it? 5796 Loop (for each) over an array in JavaScript 4995 How do I check if an array includes a value in JavaScript? 4091 Loop through an array in JavaScript 5157 What is the most efficient way to deep clone an object in JavaScript? 4457 Which \"href\" value should I use for JavaScript links, \"#\" or \"javascript: void(0)\"? 3835 Get the current URL with JavaScript? 2426 How can I add new array elements at the beginning of an array in JavaScript? Hot Network Questions c++ format_to verbosity Which vampiric power is being referenced in the following conversation? Meaning of '#' suffix on SQL Server columns What did Jesus eat in relationship to his Jewish culture and tradition? Can I say \"inbound/outbound trips/journeys/visits to/from somewhere\"? Would it be reasonable for a theist to claim that an atheist cannot appeal to any convention or apparatus of logic if there is no foundational agent? Uniform convergence of metrics imply that induced topologies are equal and possible error in Burago, Ivanov's \"A Course in Metric Geometry\" Volume-preserving fluid flows are incompressible. What about surface-area preserving flows? How to write \"the positive sign is replaced by negative sign and negative sign by positive sign\"? Does Jesus' statement in Luke 21: 19 indicate that Stephen acted without the wisdom he should have received? Naming of parent keys and their modes Does Innate Sorcery grant Advantage to True Strike? Is it correct for a rotating uniform charged ring to have current? Interesting examples of non-isomorphic groups where the probability distribution of the number of square roots of elements is the same Birth control and the ambassador of the 22nd century Why does MathML display differentiation operator weirdly when using ⅆ ? How to sync Thunderbird emails, over two computers? SAS hard drives are not accessible after removing RAID and using IT Mode Dividing both the interior and the boundary of a square into equal parts using polyominos Minimal C++ Coroutine Scheduler with Sleep, Spawn, and Join Support Does the Apollo Command Module retain its docking probe for the return to Earth? What is a sub-Gaussian distribution? How can I attach the bottom of a window A. C. unit to the bottom of a window? \"seen as X\" - sicut, ablative of means, other? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 3186,
- "timestamp": "2025-09-03 07:33:11"
- }
- },
- {
- "id": "f9f7677e75da",
- "url": "https://stackoverflow.com/questions/43823289/how-to-import-image-svg-png-in-a-react-component",
- "title": "javascript - How to import image (.svg, .png ) in a React Component - Stack Overflow",
- "content": "How to import image (. svg, . png ) in a React Component Ask Question Asked 8 years, 4 months ago Modified 3 years, 4 months ago Viewed 642k times 162 I am trying to import an image file in one of my react component. I have the project setup with web pack Here's my code for the component \n\n```\nimport Diamond from '../../assets/linux_logo.jpg';\n export class ItemCols extends Component {\n render(){\n return (\n
\n \n \n \n
\n )\n } \n}\n```\n\n Here's my project structure. I have setup my webpack. config. js file in the following way \n\n```\n{\n test: /\\.(jpg|png|svg)$/,\n loader: 'url-loader',\n options: {\n limit: 25000,\n },\n},\n{\n test: /\\.(jpg|png|svg)$/,\n loader: 'file-loader',\n options: {\n name: '[path][name].[hash].[ext]',\n },\n},\n```\n\n PS. I can get image from any other remote source but not locally saved images. The JavaScript Console also doesn't give me any error. Please anything helps. I am quite new to react and unable to find what am I doing wrong. javascript reactjs webpack Share Improve this question Follow edited Jun 25, 2018 at 8: 49 OZZIE 7, 468 10 10 gold badges 64 64 silver badges 65 65 bronze badges asked May 6, 2017 at 17: 17 Shadid 4, 292 9 9 gold badges 33 33 silver badges 54 54 bronze badges 5 3 Shadid, did you try ? Naga Sai A – Naga Sai A 05/06/2017 17: 20: 40 Commented May 6, 2017 at 17: 20 yes I tried that. Again no error in the console but I see no image Shadid – Shadid 05/06/2017 17: 29: 33 Commented May 6, 2017 at 17: 29 1 You should do a webpack build and check where the images are stored. Use that path in img src. vijayst – vijayst 05/06/2017 17: 29: 52 Commented May 6, 2017 at 17: 29 @vijayst Bless you good sir. . That worked.: ) Shadid – Shadid 05/06/2017 17: 36: 16 Commented May 6, 2017 at 17: 36 I've been struggling with this for hours. Why is it so hard to get a single logo image imported and looking right in React? It used to be so easy with plain HTML. . . Jerry Chen – Jerry Chen 07/29/2022 22: 50: 05 Commented Jul 29, 2022 at 22: 50 Add a comment | 11 Answers 11 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 254 try using \n\n```\nimport mainLogo from'./logoWhite.png';\n//then in the render function of Jsx insert the mainLogo variable\nclass NavBar extends Component {\n render() {\n return (\n \n );\n }\n}\n```\n\n Share Improve this answer Follow edited Aug 5, 2019 at 16: 40 Treycos 7, 493 3 3 gold badges 28 28 silver badges 53 53 bronze badges answered Jul 29, 2017 at 9: 50 user5660307 9 16 What would happen if I want to import 10 images? Leo Gasparrini – Leo Gasparrini 02/05/2018 19: 06: 20 Commented Feb 5, 2018 at 19: 06 5 @LeoGasparrini - I'm not sure I understand what you're asking-- you should be able to import as many as you wish as long as you give them unique names at import, no? Alexander Nied – Alexander Nied 03/06/2018 18: 43: 47 Commented Mar 6, 2018 at 18: 43 1 I am trying the same approach and babel is complaining as it's not able to understand what a png file is. How can I let babel skip png files from transpiling? Sanish Joseph – Sanish Joseph 11/07/2018 02: 28: 28 Commented Nov 7, 2018 at 2: 28 2 is possible to re export from index. ts and access multiple image like this \"import { image1, image2, image3} from '. /. . /images' \"? ? ksh – ksh 08/09/2020 18: 23: 49 Commented Aug 9, 2020 at 18: 23 2 For the curious minds out there, when we import an image like this, mainLogo is actually either a data URI (data: image/png; . . . . ) or a public URL (/static/logoWhite. svg) which dependss on your bundler. d_bhatnagar – d_bhatnagar 10/24/2020 16: 08: 34 Commented Oct 24, 2020 at 16: 08 | Show 4 more comments 20 You can use require as well to render images like \n\n```\n//then in the render function of Jsx insert the mainLogo variable\nclass NavBar extends Component {\n render() {\n return (\n \n );\n }\n}\n```\n\n Share Improve this answer Follow edited Aug 5, 2019 at 16: 40 Treycos 7, 493 3 3 gold badges 28 28 silver badges 53 53 bronze badges answered Oct 12, 2018 at 18: 04 Hemadri Dasari Hemadri Dasari 34. 2k 41 41 gold badges 124 124 silver badges 166 166 bronze badges 1 1 When I tried this solution I got this error \n\n```\n[HMR] unexpected require(./src/components/LeftBar/home.svg) from disposed module ./src/components/LeftBar/LeftBar.js LeftBar App@http://localhost:3000/static/js/main.chunk.js:115:79\n```\n\n Do you know whats happen? Thank You Roby Cigar – Roby Cigar 01/18/2021 10: 12: 06 Commented Jan 18, 2021 at 10: 12 Add a comment | 13 If the images are inside the src/assets folder you can use \n\n```\nrequire\n```\n\n with the correct path in the require statement, \n\n```\nvar Diamond = require('../../assets/linux_logo.jpg');\n export class ItemCols extends Component {\n render(){\n return (\n
\n \n \n \n
\n )\n } \n}\n```\n\n Share Improve this answer Follow answered May 30, 2018 at 5: 42 Rohith Murali Rohith Murali 5, 679 2 2 gold badges 27 27 silver badges 28 28 bronze badges Add a comment | 7 There are few steps if we dont use \"create-react-app\", ( [email protected] ) first we should install file-loader as devDedepencie, next step is to add rule in webpack. config \n\n```\n{\n test: /\\.(png|jpe?g|gif)$/i,\n loader: 'file-loader',\n}\n```\n\n, then in our src directory we should make file called declarationFiles. d. ts(for example) and register modules inside \n\n```\ndeclare module '*.jpg';\ndeclare module '*.png';\n```\n\n, then restart dev-server. After these steps we can import and use images like in code bellow \n\n```\nimport React from 'react';\nimport image from './img1.png';\nimport './helloWorld.scss';\nconst HelloWorld = () => (\n <>\n
React TypeScript Starter
\n \n >\n);\nexport default HelloWorld;\n```\n\n Works in typescript and also in javacript, just change extension from. ts to. js Cheers. Share Improve this answer Follow edited Feb 25, 2021 at 11: 10 answered Feb 25, 2021 at 9: 50 Goran_Ilic_Ilke 888 13 13 silver badges 17 17 bronze badges 1 what abut path intellisense? how to get it work? Ozan Mudul – Ozan Mudul 03/01/2023 10: 49: 27 Commented Mar 1, 2023 at 10: 49 Add a comment | 7 Create a folder and name it as \n\n```\nimages.ts\n```\n\n or \n\n```\nimages.js\n```\n\n in your assets folder or anywhere you wish. Export all images in a folder using the \n\n```\nexport {default as imageName} from 'route'\n```\n\n statement. \n\n```\nexport { default as image1 } from \"assets/images/1.png\";\nexport { default as image2 } from \"assets/images/2.png\";\nexport { default as image3 } from \"assets/images/3.png\";\nexport { default as image4 } from \"assets/images/4.png\";\n```\n\n then import images using the \n\n```\nimport {imageDefaultName} from 'route'\n```\n\n \n\n```\nimport {image1,image2,image3,image4} from 'assets/images'\n\n\n\n\n```\n\n OR \n\n```\nimport * as images from 'assets/images'\n\n\n\n\n```\n\n Share Improve this answer Follow edited Apr 11, 2022 at 2: 44 answered Apr 10, 2022 at 17: 42 Ridwan Ajibola Ridwan Ajibola 1, 099 14 14 silver badges 20 20 bronze badges 2 Cannot find module \n\n```\n\"assets/images/1.png\"\n```\n\n or its corresponding type declarations. Arajay – Arajay 12/05/2023 00: 02: 22 Commented Dec 5, 2023 at 0: 02 Did you save the image in \n\n```\n\"assets/images/\"\n```\n\n folder? You have to save the image your own project folder and then reference it from there. Ridwan Ajibola – Ridwan Ajibola 12/06/2023 14: 12: 41 Commented Dec 6, 2023 at 14: 12 Add a comment | 3 You can also try: \n\n```\n...\nvar imageName = require('relative_path_of_image_from_component_file');\n...\n...\nclass XYZ extends Component {\n render(){\n return(\n ...\n \n ...\n )\n }\n}\n...\n```\n\n Note: Make sure Image is not outside the project root folder. Share Improve this answer Follow answered Jan 24, 2021 at 15: 59 Mayank Pathela Mayank Pathela 668 1 1 gold badge 10 10 silver badges 22 22 bronze badges Add a comment | 2 To dynamically import an image using a variable, you can use the following: \n\n```\nconst imageName = \"myImage.png\"\n const images = require.context('../images',true);\n const [imgUrl, setImgUrl] = useState('');\n useEffect(() => {\n if (images && imageName) {\n setImgUrl(\n images(`./${imageName}`).default\n );\n }\n }, [imageName,images]);\n ...\n \n```\n\n Share Improve this answer Follow answered Oct 4, 2021 at 18: 38 Jöcker 7, 028 3 3 gold badges 45 45 silver badges 53 53 bronze badges Add a comment | 1 I also had a similar requirement where I need to import. png images. I have stored these images in public folder. So the following approach worked for me. \n\n```\n\n```\n\n In addition to the above I have tried using require as well and it also worked for me. I have included the images inside the Images folder in src directory. \n\n```\n\n```\n\n Share Improve this answer Follow answered Sep 5, 2020 at 12: 26 Senthuran 1, 877 2 2 gold badges 19 19 silver badges 20 20 bronze badges Add a comment | 0 \n\n```\nimport React, {Component} from 'react';\nimport imagename from './imagename.png'; //image is in the current folder where the App.js exits\nclass App extends React. Component{\n constructor(props){\n super(props)\n this.state={\n imagesrc=imagename // as it is imported\n }\n }\n render(){\n return (\n \n );\n }\n}\nclass ImageClass extends React.Component{\n render(){\n return (\n \n );\n }\n}\nexport default App;\n```\n\n Share Improve this answer Follow edited May 19, 2019 at 13: 09 answered May 19, 2019 at 13: 03 Matiullah Mosazai Matiullah Mosazai 71 3 3 bronze badges Add a comment | 0 I used user5660307 answer. And also for server-side rendering using react and nodejs, you can add this in express server: \n\n```\napp.use(express.static(\"public\"));\n```\n\n and in webpack. client. js: \n\n```\nmodule.exports = {\n entry: \"./src/client/client.js\",\n output: {\n filename: \"bundle.js\",\n path: path.resolve(__dirname, \"public\"),\n },\n module: {\n rules: [\n ...\n {\n loader: require.resolve(\"file-loader\"),\n exclude: [/\\.(js|mjs|jsx|ts|tsx)$/, /\\.html$/, /\\.json$/],\n options: {\n name: \"static/media/[name].[hash:8].[ext]\",\n },\n },\n {\n test: [/\\.bmp$/, /\\.gif$/, /\\.jpe?g$/, /\\.png$/],\n loader: require.resolve(\"url-loader\"),\n options: {\n name: \"static/media/[name].[hash:8].[ext]\",\n },\n },\n ],\n },\n};\n```\n\n Share Improve this answer Follow edited Jul 22, 2021 at 12: 41 answered Jul 22, 2021 at 12: 28 H Ketabi H Ketabi 3, 164 3 3 gold badges 25 25 silver badges 32 32 bronze badges Add a comment | -2 Solved the problem, when moved the folder with the image in src folder. Then I turned to the image (project created through \"create-react-app\") let image = document. createElement(\"img\"); image. src = require('. . /assets/police. png'); Share Improve this answer Follow answered May 27, 2018 at 18: 16 Andre 9 1 Could be and so: import React, { Component } from 'react'; export default class Lesson3 extends Component { render() { return ( ); } } Andre – Andre 05/27/2018 18: 20: 35 Commented May 27, 2018 at 18: 20 Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript reactjs webpack See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 13 Why do I have to use \"require\" instead of \"import from\" for an image in React? 2 importing images locally in react 1 How to import image from external folders in react 0 Can't display images from local server on react js 1 Importing Images as props using the. map syntac(React and Material ui) 0 Unable to resolve an image in an array in React JS 1 Unable to display photo in react create app project 0 Custom Text Field with icon at start of the Text Field with the variant type \"outlined\" in material-ui 0 ES6 Dynamic importing issues 0 uploading image in python flask server and display image in react frontend See more linked questions Related 4 How to import svg files and use them for src in image 1 Not able to import SVG image into my typescript application 2 Can I import a png/jpg image like a component? React. js 0 Import image in reactjs 1 How to import image(SVG or PNG) in React using Create React App 0 Is there a way to import SVG images as a component? 6 How to import a svg file in React? 4 How to import a local SVG file in React? 0 How to import svg saved as js file in react 3 Importing img instead of SVG Hot Network Questions In Luke 21: 16, is ‘they will put some of you to death’ meant literally or symbolically? Looking for a short story collection, history of the universe starting with the big bang Do C++20 attributes [[likely]] and [[unlikely]] have anything to do with \"Speculative Execution\"? In \"Little Women\" (1949), what is the German song sung and played on the piano by Professor Bhaer? What is this slot in the Cessna 152's interior sidewall? Do the Apollo probe/drogues also serve as an airtight seal when not docked, or is there a separate seal? When would a court impose a harsher sentence than the prosecutor requests? In what American magazine was Tolkien's \"Smith of Wootton Major\" first published? Is a condition termed a \"disease\" only when it has a known cause? Weird set builder notation I can't find elsewhere Extra space after \\left…\\right workaround with \\vphantom in LaTeX What do I do if a DB Bahn train is late for an OBB connection? Does Japanese have a gender-neutral third person pronoun? Which vampiric power is being referenced in the following conversation? Does the Apollo Command Module retain its docking probe for the return to Earth? How to show that the complement of an Archimedean spiral is open and connected? How does one get more oxyfern? Is it correct for a rotating uniform charged ring to have current? Volume-preserving fluid flows are incompressible. What about surface-area preserving flows? What was the first game where your guide/quest giver turned out to be a key antagonist/villain? Can I say \"inbound/outbound trips/journeys/visits to/from somewhere\"? Would this weapon be good for catching melee weapons? Program Generator: Print a Paragraph What is the measure of the new angle? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.5,
- "coherence_score": 7.0,
- "word_count": 2587,
- "timestamp": "2025-09-03 07:33:13"
- }
- },
- {
- "id": "6e9f373dbeb9",
- "url": "https://www.javascripttutorial.net/",
- "title": "JavaScript Tutorial",
- "content": "Welcome to the JavaScriptTutorial. net website! This JavaScript Tutorial helps you learn the JavaScript programming language from scratch quickly and effectively. If you find yourself in any of the following situations: Unsure about where to start learning JavaScript. Tired of simply copying and pasting JavaScript code without really understanding how it works. Feel stuck to add richer and more compelling features to your websites and web applications because you don’t know how to get much out of JavaScript. JavaScriptTutorial. net is a good place to start. Section 1. Getting started What is JavaScript? – introduce you to JavaScript and its history. Install a JavaScript source code editor – learn how to install the Visual Studio Code for editing JavaScript code. Meet the Console Tab of Web Development Tools – provide you with a basic introduction to the Console window on the web browsers. JavaScript Hello World – learn how to execute the first JavaScript code that displays the famous \n\n```\n\"Hello, World!\"\n```\n\n message. Section 2. Fundamentals Syntax – explain the JavaScript syntax, including whitespace, statements, identifiers, keywords, expressions, and comments. Variables – show you how to declare variables. Data types – introduce to you the JavaScript data types, including primitive and reference types. Number – learn how JavaScript uses the \n\n```\nNumber\n```\n\n type to represent the integer and floating-point numbers. Numeric Separator – show you how to make the numbers more readable by using underscores as numeric separators. Octal & binary literals – provide support for binary literals and change the way to represent octal literals. Boolean – introduce you to the \n\n```\nBoolean\n```\n\n type. String – learn about string primitive type and some basic string operations. Object – introduce you to the object type. Primitive vs. reference values – understand two value types in JavaScript, including primitive and reference values, and the differences between them. Array – introduce you to the \n\n```\nArray\n```\n\n type and how to manipulate array elements. Section 3. Operators Arithmetic operators – introduce to you the arithmetic operators including addition ( \n\n```\n+\n```\n\n ), subtraction ( \n\n```\n-\n```\n\n ), multiplication ( \n\n```\n*\n```\n\n ), and division ( \n\n```\n/\n```\n\n ). Remainder operator – show you how to use the remainder operator ( \n\n```\n%\n```\n\n ) to get the remainder left over when one value is divided by another value. Assignment operators – guide you on how to use assignment operators ( \n\n```\n=\n```\n\n ) to assign a value or an expression to a variable. Unary operators – learn how to use unary operators. Comparison operators – show you how to use comparison operators to compare two values. Logical operators – learn how to use the logical operators: NOT ( \n\n```\n!\n```\n\n ), AND ( \n\n```\n&&\n```\n\n ), and OR ( \n\n```\n||\n```\n\n ). Section 4. Control flow Statements if – show you how to use the \n\n```\nif\n```\n\n statement to execute a block if a condition is true. if…else – learn how to execute a block of code based on a specified condition. if…else…if – check multiple conditions and execute a block. Ternary operators – show you how to make a shortcut for the \n\n```\nif\n```\n\n statement ( \n\n```\n?:\n```\n\n ). switch – show you how to replace multiple \n\n```\nif\n```\n\n statements when comparing a value with multiple variants by using the \n\n```\nswitch\n```\n\n statement. while – learn how to perform a pre-test loop that repeatedly executes a block of code as long as a specified condition is \n\n```\ntrue\n```\n\n. do…while – show you how to carry a post-test loop that executes a block of code repeatedly until a specified condition is \n\n```\nfalse\n```\n\n. for loop – learn how to repeatedly execute a block of code based on various options. break – learn how to prematurely terminate a loop. continue – show you how to skip the current iteration of a loop and jump to the next one. Comma operator – guide you on how to use the comma operator in a \n\n```\nfor\n```\n\n loop to update multiple variables at once. Section 5. Functions – introduce you to functions in JavaScript. Functions are first-class citizens – learn how to store functions in the variables, pass functions into other functions as arguments, and return functions as values. Anonymous Functions – learn about anonymous functions which are the functions without names. Pass-by-value – understand how pass-by-value works in JavaScript. Recursive function – learn how to define recursive functions. Default Parameters – show you how to define default parameters for functions. Section 6. Objects & Prototypes Object Methods – introduce you to the methods of an object. Constructor functions – show you how to use constructor functions to define custom types in JavaScript. Prototype – learn how the prototype works in JavaScript. Constructor/Prototype pattern – show you how to combine the constructor function and prototype pattern to define custom types. Prototypal inheritance – understand prototypal inheritance in JavaScript. What is this in JavaScript – understand the \n\n```\nthis\n```\n\n value and how it works in JavaScript. globalThis – provide a standard way to access the global object across environments. Object Properties – dive into the object’s properties and their attributes. for…in loop – learn how to iterate over properties of an object using the \n\n```\nfor...in\n```\n\n loop. Enumerable Properties – learn more about the enumerable properties. Own Properties – understand the own and inherited properties. Factory functions – learn about the factory functions which are functions that return objects. Object Destructuring – learn how to assign properties of an object to variables. Optional chaining operator ( \n\n```\n?.\n```\n\n ) – simplify the way to access a property located deep within a chain of connected objects without having to check if each reference in the chain is \n\n```\nnull\n```\n\n or \n\n```\nundefined\n```\n\n. Object literal syntax extensions – provide a new way to define object literal. Section 7. Classes Class – introduce you to the ES6 class syntax and how to declare a class. Getters and Setters – define the getters and setters for a class using the get and set keywords. Class Expression – learn an alternative way to define a new class using a class expression. Computed property – explain the computed property and its practical application. Inheritance – show you how to extend a class using the \n\n```\nextends\n```\n\n and \n\n```\nsuper\n```\n\n keywords. new. target – introduce you to the \n\n```\nnew.target\n```\n\n metaproperty. Static methods – guide you on how to define methods associated with a class, not instances of that class. Static Properties – show you how to define static properties shared by all instances of a class. Private Fields – learn how to define private fields in a class. Private Methods – show you how to define private methods in a class. Section 8. Advanced Functions Function type – introduce you to the \n\n```\nFunction\n```\n\n type and its properties and methods. call() – understand the \n\n```\ncall()\n```\n\n method and learn how to use it effectively. apply() – learn how to use the \n\n```\napply()\n```\n\n method effectively. bind() – understand the \n\n```\nbind()\n```\n\n method and how to apply it effectively. Closure – understand the closures in JavaScript. Immediately Invoked Function Expression (IIFE) – learn about immediately invoked function expressions (IIFE). Returning multiple values – guide you on how to return multiple values from a function. Arrow functions – introduce you to the arrow functions ( \n\n```\n=>\n```\n\n ) Arrow functions: when you should not use – learn when not to use arrow functions. Rest parameter – introduce you to the rest parameters and how to use them effectively. Callback functions – introduce you to the callback functions and learn how to use the callbacks to handle asynchronous operations. Section 9. Promises & Async/Await Promises – learn about Javascript Promises, what they are, and how to use them effectively. Promise chaining – show you how to execute multiple asynchronous operations in sequence. Promise composition: \n\n```\nPromise.all()\n```\n\n & \n\n```\nPromise.race()\n```\n\n – learn how to compose a new promise out of several promises. Promise. any() – learn how to use the JavaScript \n\n```\nPromise.any()\n```\n\n method to return the first \n\n```\nPromise\n```\n\n that fulfills. Promise. allSettled() – accept a list of promises and returns a new promise that resolves to an array of values, which were settled (either resolved or rejected) by the input promises. Promise. prototype. finally() – execute a piece of code when the promise is settled, regardless of its outcome. Promise error handling – guide you on how to handle errors in promises. async / await – write asynchronous code in a clearer syntax. Promise. withResolvers() – return a new Promise with resolve and reject functions. Section 10. Iterators & Generators Iterators – introduce you to the iteration and iterator protocols. Generators – develop functions that can pause midway and then continue from where they paused. yield – dive into how to use the \n\n```\nyield\n```\n\n keyword in generators. for…of – learn how to use the \n\n```\nfor...of\n```\n\n loop to iterate over elements of an iterable object. Asynchronous iterators – learn how to use asynchronous iterators to access asynchronous data sources sequentially. Async generators – show you how to create an async generator. Section 11. Modules – learn how to write modular JavaScript code. Export – explain in detail how to export variables, functions, and classes from a module. Import – guide you on how to import default exports and named exports from another module. Dynamic import – show you how to import a module dynamically via the function-like object \n\n```\nimport()\n```\n\n. Top-level await – explain the top-level await module and its use cases. Section 12. Symbol – introduce you to a new primitive type called \n\n```\nsymbol\n```\n\n in ES6 Section 13. Collections Map – introduce you to the \n\n```\nMap\n```\n\n type that holds a collection of key-value pairs. Set – learn how to use the \n\n```\nSet\n```\n\n type that holds a collection of unique values. Section 14. Error handling try…catch – show you how to handle exceptions gracefully. try…catch…finally – learn how to catch exceptions and execute a block whether the exceptions occur or not. throw – show you how to throw an exception. Optional catch binding – omit the exception variable in the catch block. Section 15. JavaScript var, let, and const let – declare block-scoped variables using the \n\n```\nlet\n```\n\n keyword. let vs. var – understand the differences between \n\n```\nlet\n```\n\n and \n\n```\nvar\n```\n\n. const – define constants using the \n\n```\nconst\n```\n\n keyword. Section 16. Proxy & Reflection Proxy – learn how to use the proxy object that wraps another object (target) and intercepts the fundamental operations of the target object. Reflection – show you how to use ES6 Reflection API to manipulate variables, properties, and methods of objects at runtime. Section 17. JavaScript Runtime Execution Contexts – understand execution contexts including global and function execution contexts. Call Stack – understand the call stack. Event Loop – show you how JavaScript handles asynchronous operations using the event loop. Hoisting – learn how hoisting works in JavaScript. Variable scopes – introduce you to the variable scopes. Section 18. Primitive Wrapper Types Primitive wrapper types – learn how primitive wrapper types work in JavaScript. Boolean – introduce you to the Boolean primitive wrapper type. Number – learn about the Number primitive wrapper type. BigInt – introduce the \n\n```\nBigInt\n```\n\n type that represents the big integers. String type – introduce you to the String type. Section 19. Advanced Operators Logical assignment operators – introduce to you the logical assignment operators, including \n\n```\n||=\n```\n\n, \n\n```\n&&=\n```\n\n, and \n\n```\n??=\n```\n\n Nullish coalescing operator ( \n\n```\n??\n```\n\n ) – accept two values and return the second value if the first one is \n\n```\nnull\n```\n\n or \n\n```\nundefined\n```\n\n. Exponentiation operator – introduce you to the exponentiation operator ( \n\n```\n**\n```\n\n ) that calculates a base to the exponent power, which is similar to \n\n```\nMath.pow()\n```\n\n method.",
- "metadata": {
- "source_type": "tutorial",
- "quality_score": 9.2,
- "coherence_score": 7.0,
- "word_count": 2029,
- "timestamp": "2025-09-03 07:32:49"
- }
- },
- {
- "id": "5e537c59dccb",
- "url": "https://stackoverflow.com/questions/tagged/reactjs+javascript",
- "title": "Newest 'reactjs+javascript' Questions - Stack Overflow",
- "content": "All Questions Ask Question Tagged with reactjs javascript 206, 618 questions Newest Active Bountied Unanswered More Bountied 0 Unanswered Frequent Score Trending Week Month Unanswered (my tags) Filter by No answers No upvoted or accepted answers No Staging Ground Has bounty Days old Sorted by Newest Recent activity Highest score Most frequent Bounty ending soon Trending Most activity Tagged with My watched tags The following tags: Apply filter Cancel 0 votes 1 answer 30 views how to place the co-ordinates of View to the absolute View in react native I'm trying to create shared-element transition. Using ref i'm accessing the View location (height, width, pageX, pageY) from measure method and i have another View with absolute position where i'm. . . javascript css reactjs react-native Karan Vishwakarma 3 asked 13 hours ago 0 votes 1 answer 46 views React Virtualized MultiGrid: Box shadow on first fixed column appears on left instead of right I’m using React Virtualized MultiGrid and trying to add a box shadow to the first fixed column. I am able to apply the box shadow, but it always appears on the left side, whereas I need it on the. . . javascript html css reactjs Aman Sadhwani 3, 616 asked 13 hours ago 2 votes 1 answer 50 views React Router Nested Routes I'm having issues configuring react-router-dom with nested routes loaded by sub-modules. In my application I need to dynamically load modules that have their own nested routes. One of the requirement. . . javascript reactjs react-router nested-routes cef62 33 asked 15 hours ago 1 vote 3 answers 66 views Is there way to use Symbol in React JS like base for key in map function By the React docs is specified that key value in React lists should be unique. So, in that way, best choice is use ids from our database on client side like a key when we use map for our lists. But if. . . javascript reactjs typescript Mikhail 25 asked 16 hours ago 0 votes 1 answer 50 views How to get contentWindow of iframe without mounting to DOM I’m working on a React app where I need to manage multiple iframes dynamically. Each iframe is created only once and stored in a cache (Map/Ref) for reuse. At any given time, only the selected iframe. . . javascript reactjs react-native iframe frontend Nandha Kumar V C 9 asked 21 hours ago -1 votes 0 answers 47 views Configuring ConsoleNinja to run in VSCode I have installed ConsoleNinja extention in VSCode. In powershell terminal, i run index. js file using node index. js I get the output of my index. js file but don't see console. log message values I am. . . javascript reactjs node. js powershell vscode-extensions gram77 537 asked 22 hours ago 1 vote 0 answers 35 views Inkscape SVG misaligned when put into React+Vite project and won't rotate around hinge I am making a microfuge tube that has two groups: the cap and the body. I used Inkscape to make the microfuge tube, and then I ran the XML file through Chat GPT to get a simplified version of the SVG. . . javascript reactjs svg inkscape Matteo Agastra 11 asked yesterday 0 votes 1 answer 53 views How to get restricted image via URL? I have been trying to get access to an image I uploaded to Cloudinary and later made it restricted. The method I want to use is using it's URL but for some reason no URL works and it's documentation. . . javascript reactjs cloudinary TheSpy181 1 asked yesterday -3 votes 1 answer 47 views Is it still necessary to use 'useEffectEvent' function [closed] When I read the react document, I found a new feature useEffectEvent, which raised a question. If I use responsive variables A and B in useEffect, but I am very sure that it is meaningful to make the. . . javascript reactjs events react-hooks zhunbe 7 asked yesterday -1 votes 0 answers 51 views How to display a variable in an animated image/video in JS? [closed] There is a task: add an animation file to a Vue3 web application and embed a variable in a specific place in the animation. The variable is a changing number that should be bound to a specific visual. . . javascript reactjs vuejs3 Alex Tuiasosopo 3 asked 2 days ago -1 votes 0 answers 43 views How to set a class to dynamically rendered button via Grid? [closed] I am trying to implement responsive and dynamic grid design into my calculator. I know of a simple way of achieving this(explicitly create buttons and add classes), but I am trying to find out if. . . javascript reactjs css-grid VXVNII 7 asked 2 days ago 1 vote 0 answers 71 views CSS transition not working when moving tile down in React sliding puzzle I'm building a sliding puzzle game in React using CSS transitions to animate tile movement. The tiles are absolutely positioned with top and left, and I apply a CSS transition on those properties. . . . javascript css reactjs Sebu 15 asked 2 days ago -2 votes 0 answers 45 views Arrow keys for month selection and clicking on month to select month in date picker, both not working [closed] Moodboard. jsx Generated. jsx calendar. jsx (this is included in both moodboard. jsx and generated. jsx) Issue: In the date picker in Generated. jsx, when I click on the month to select what month's. . . javascript css reactjs Hardik Kalra 1 asked 2 days ago -2 votes 0 answers 45 views Why are Socket. io or WebSockets used in React applications? [closed] Socket. io or WebSockets are used in React applications for **real-time communication Normally, React fetches data using HTTP requests (GET, POST), which work on a request-response cycle. But for. . . javascript reactjs websocket socket. io real-time Huzaifa Imran 1 asked Aug 30 at 21: 45 -1 votes 0 answers 36 views THREE. js depth-map parallax looks “off” / swimming—how do I correctly align depth with the texture? [closed] I’m building a layered parallax effect in React + THREE. js where each PNG texture has a matching grayscale depth map. The scene renders and the mouse parallax works, but the motion looks unnatural—. . . javascript reactjs three. js shader fragment-shader Base 1 asked Aug 30 at 15: 10 15 30 50 per page 1 2 3 4 5 … 13775 Next The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Hot Network Questions xargs -I {} not replacing with input string, says \"/usr/bin/xargs: {}: No such file or directory\" What was the first game where your guide/quest giver turned out to be a key antagonist/villain? In what American magazine was Tolkien's \"Smith of Wootton Major\" first published? Does Japanese have a gender-neutral third person pronoun? How to find \"minimal polynomial\" of a rational number? Does Jesus' statement in Luke 21: 19 indicate that Stephen acted without the wisdom he should have received? Why did Hashem try killing Moses on his way to Egypt? Is a condition termed a \"disease\" only when it has a known cause? Have there been any 20th century onwards notable rabbanim from the Indian Jewish community? SAS hard drives are not accessible after removing RAID and using IT Mode Is it correct for a rotating uniform charged ring to have current? What natural predators would prove the most dangerous for a village of tiny 5 inch people? Weird set builder notation I can't find elsewhere What are the biblical arguments against the idea of a post-mortem opportunity for salvation? Minimal C++ Coroutine Scheduler with Sleep, Spawn, and Join Support Uniform convergence of metrics imply that induced topologies are equal and possible error in Burago, Ivanov's \"A Course in Metric Geometry\" How to prove that natural number less than is irrelevant? Birth control and the ambassador of the 22nd century How to merge two tables with a different amount of columns in one table? What do I do if a DB Bahn train is late for an OBB connection? Does the Apollo Command Module retain its docking probe for the return to Earth? Knowledge is free, but time costs money? Does Innate Sorcery grant Advantage to True Strike? A question on the paper \"Maximal unramified extensions of imaginary quadratic number fields of small conductors\" more hot questions Newest reactjs javascript questions feed",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.2,
- "coherence_score": 6.0,
- "word_count": 1433,
- "timestamp": "2025-09-03 07:32:53"
- }
- },
- {
- "id": "f641658117e4",
- "url": "https://stackoverflow.com/questions/34883068/how-to-get-first-n-number-of-elements-from-an-array",
- "title": "javascript - How to get first N number of elements from an array - Stack Overflow",
- "content": "How to get first N number of elements from an array Ask Question Asked 9 years, 7 months ago Modified 2 years, 1 month ago Viewed 1. 4m times 1209 I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n). In my Jsx file I have the following: \n\n```\nvar items = list.map(i => {\n return (\n \n );\n});\n```\n\n Then to get the first 3 items I tried \n\n```\nvar map = new Map(list);\n map.size = 3;\n var items = map(i => {\n return ();\n });\n```\n\n This didn't work as map doesn't have a set function. What can I try next? javascript arrays filtering slice extract Share Improve this question Follow edited Feb 21, 2023 at 15: 16 halfer 20. 1k 19 19 gold badges 110 110 silver badges 207 207 bronze badges asked Jan 19, 2016 at 17: 19 user1526912 17. 4k 18 18 gold badges 62 62 silver badges 98 98 bronze badges 0 Add a comment | 13 Answers 13 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 1837 To get the first \n\n```\nn\n```\n\n elements of an array, use \n\n```\nconst slicedArray = array.slice(0, n);\n```\n\n Share Improve this answer Follow edited Jul 20, 2023 at 13: 17 deb 7, 531 2 2 gold badges 14 14 silver badges 27 27 bronze badges answered Jan 19, 2016 at 17: 23 Oriol 290k 71 71 gold badges 458 458 silver badges 535 535 bronze badges 8 209 Note that the \n\n```\nslice\n```\n\n function on arrays returns a shallow copy of the array, and does not modify the original array. developer. mozilla. org/en-US/docs/Web/JavaScript/Reference/… Danny Harding – Danny Harding 07/13/2018 01: 34: 11 Commented Jul 13, 2018 at 1: 34 56 Does this throw any error if n is larger than size? Rishabh876 – Rishabh876 09/28/2020 08: 56: 40 Commented Sep 28, 2020 at 8: 56 72 @Rishabh876 No it does not. For \n\n```\narray.slice(0, n);\n```\n\n it returns \n\n```\n[0, min(n, array.length))\n```\n\n. Morgoth – Morgoth 10/21/2020 09: 07: 50 Commented Oct 21, 2020 at 9: 07 2 @Morgoth - I'm confused here -- are you saying this is incorrect because, in cases when the array has less than 3 elements, this method won't return 3 elements? ashleedawg – ashleedawg 09/20/2021 09: 25: 36 Commented Sep 20, 2021 at 9: 25 6 @ashleedawg Depends on your definition of correct. If \n\n```\narray\n```\n\n has less than 3 elements and you slice it for 3, then it will return all the elements in the array (i. e. less than 3). That is a very sensible behaviour, but if that does not make sense for your application you might want to check the length of the array first. Morgoth – Morgoth 09/20/2021 09: 44: 23 Commented Sep 20, 2021 at 9: 44 | Show 3 more comments 867 I believe what you're looking for is: \n\n```\n// ...inside the render() function\nvar size = 3;\nvar items = list.slice(0, size).map(i => {\n return \n}); \nreturn (\n
\n {items}\n
\n)\n```\n\n Share Improve this answer Follow edited Feb 17, 2022 at 13: 52 Mdr Kuchhadiya 461 5 5 silver badges 18 18 bronze badges answered Jan 19, 2016 at 17: 33 Patrick Shaughnessy Patrick Shaughnessy 8, 990 1 1 gold badge 12 12 silver badges 6 6 bronze badges 0 Add a comment | 92 \n\n```\narr.length = n\n```\n\n This might be surprising but \n\n```\nlength\n```\n\n property of an array is not only used to get number of array elements but it's also writable and can be used to set array's length MDN link. This will mutate the array. If you don't care about immutability or don't want to allocate memory i. e. for a game this will be the fastest way. to empty an array \n\n```\narr.length = 0\n```\n\n Share Improve this answer Follow edited Jan 16, 2021 at 11: 59 answered Feb 6, 2018 at 16: 02 Pawel 18. 5k 6 6 gold badges 78 78 silver badges 76 76 bronze badges 3 21 This will also expand the array if it is smaller than N Oldrich Svec – Oldrich Svec 12/02/2019 15: 41: 05 Commented Dec 2, 2019 at 15: 41 1 Pawel's answer seems the best option in resource-critical environments, and when the remaining elements can be discarded. Considering the case when the array is already smaller, this is a little improvement: \n\n```\nif (arr.length > n) arr.length = n\n```\n\n Manuel de la Iglesia Campos – Manuel de la Iglesia Campos 07/28/2021 23: 02: 31 Commented Jul 28, 2021 at 23: 02 @OldrichSvec Expand it with what? null? undefined? TheHaloDeveloper – TheHaloDeveloper 07/25/2024 15: 32: 21 Commented Jul 25, 2024 at 15: 32 Add a comment | 53 Use Slice Method The javascript \n\n```\nslice()\n```\n\n method returns a portion of an array into a new array object selected from start to end where start and end represent the index of items in that array. The original array will not be modified. syntax: \n\n```\nslice(start, end)\n```\n\n Let us say we have an array with 7 items \n\n```\n[5,10,15,20,25,30,35]\n```\n\n and we want the first 5 elements from that array: \n\n```\nlet array = [5,10,15,20,25,30,35]\nlet newArray = array.slice(0,5)\nconsole.log(newArray)\n```\n\n Share Improve this answer Follow edited Sep 14, 2021 at 13: 21 buddemat 5, 330 16 16 gold badges 37 37 silver badges 61 61 bronze badges answered Sep 14, 2021 at 13: 14 Rahul singh Rahul singh 541 4 4 silver badges 2 2 bronze badges 1 please just pay attention you'll receive the values in the array beginning with the one at index start untill the one at index end - 1. this is good to allow looping. alex – alex 06/20/2022 13: 46: 16 Commented Jun 20, 2022 at 13: 46 Add a comment | 42 You can filter using \n\n```\nindex\n```\n\n of array. \n\n```\nvar months = ['Jan', 'March', 'April', 'June'];\r\nmonths = months.filter((month,idx) => idx < 2)\r\nconsole.log(months);\n```\n\n Share Improve this answer Follow edited Feb 4, 2019 at 6: 10 answered Jan 15, 2019 at 6: 36 Freddy 2, 392 3 3 gold badges 34 34 silver badges 36 36 bronze badges 1 18 \n\n```\n.filter\n```\n\n on it's own is not a great choice, at least not if the input array might be long. \n\n```\n.filter\n```\n\n goes through every element of the array checking its condition. \n\n```\n.slice\n```\n\n would not do this, but would just extract the first n elements and then stop processing - which would definitely be what you want for a long list. (As @elQueFaltaba already said in comments to another answer. ) MikeBeaton – MikeBeaton 09/18/2019 09: 45: 57 Commented Sep 18, 2019 at 9: 45 Add a comment | 19 Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match. In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like \n\n```\nvar items = list\n .filter((i, index) => (index < 3))\n .map((i, index) => {\n return (\n \n );\n });\n```\n\n Share Improve this answer Follow edited Apr 19, 2017 at 19: 30 answered Jan 19, 2016 at 17: 33 sandeep 2, 138 1 1 gold badge 12 12 silver badges 13 13 bronze badges 2 1 You're correct overall, but semantically you should use filter to first filter down the set of elements, then, map the filtered down set if you are taking this approach. Chris – Chris 04/11/2017 09: 05: 52 Commented Apr 11, 2017 at 9: 05 11 The filter function would go through all the elements in the array, while the slice would not, so it's better performant-wise to use slice, right? elQueFaltaba – elQueFaltaba 06/13/2017 10: 21: 56 Commented Jun 13, 2017 at 10: 21 Add a comment | 17 Just try this to get first \n\n```\nn\n```\n\n elements from list: \n\n```\nconst slicedList = list.slice(0, n);\n```\n\n Example: \n\n```\nconst list = [1,2,3,4,5]\nconsole.log(list.slice(0, 3)) // Should return [1,2,3] \nconsole.log(list.slice(0, 10)) // Returns [1,2,3,4,5] since this is all we have in 1st 10 elements\n```\n\n Share Improve this answer Follow answered Jun 18, 2021 at 18: 19 Anurag 426 4 4 silver badges 15 15 bronze badges Add a comment | 14 [1, 2, 3, 4, 5, 6, 7, 8, 8]. slice(0, 3) = While return the first 3 elements. Answer: [1, 2, 3] How it works: The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Share Improve this answer Follow answered Nov 8, 2022 at 13: 05 Frank HN Frank HN 535 5 5 silver badges 12 12 bronze badges Add a comment | 10 The following worked for me. \n\n```\narray.slice( where_to_start_deleting, array.length )\n```\n\n Here is an example \n\n```\nvar fruits = [\"Banana\", \"Orange\", \"Apple\", \"Mango\"];\nfruits.slice(2, fruits.length);\n//Banana,Orange ->These first two we get as resultant\n```\n\n Share Improve this answer Follow edited May 1, 2019 at 11: 41 BCPNAYAK 187 3 3 gold badges 4 4 silver badges 18 18 bronze badges answered Jan 4, 2019 at 20: 24 FlyingSnowGhost 187 1 1 silver badge 3 3 bronze badges 3 4 In the first example you use \n\n```\nslice\n```\n\n but in the second you use \n\n```\nsplice\n```\n\n. Veslav – Veslav 04/12/2019 11: 44: 39 Commented Apr 12, 2019 at 11: 44 10 This is also wrong. You will get \n\n```\n[\"Apple\", \"Mango\"]\n```\n\n from this. The first part of slice is not \"where to start deleting\", it's where to start the slice from. It doesn't modify the original array and won't delete anything. Redmega – Redmega 10/02/2019 20: 10: 00 Commented Oct 2, 2019 at 20: 10 2 This is not correct. Slice returns a new array of the sliced items. Should be \n\n```\nfruits.slice(0,2)\n```\n\n, where \n\n```\n0\n```\n\n is the starting index and \n\n```\n2\n```\n\n is the number to take. developer. mozilla. org/en-US/docs/Web/JavaScript/Reference/… denski – denski 10/14/2020 20: 22: 45 Commented Oct 14, 2020 at 20: 22 Add a comment | 6 Using a simple example: \n\n```\nvar letters = [\"a\", \"b\", \"c\", \"d\"];\nvar letters_02 = letters.slice(0, 2);\nconsole.log(letters_02)\n```\n\n Output: [\"a\", \"b\"] \n\n```\nvar letters_12 = letters.slice(1, 2);\nconsole.log(letters_12)\n```\n\n Output: [\"b\"] Note: \n\n```\nslice\n```\n\n provides only a shallow copy and DOES NOT modify the original array. Share Improve this answer Follow answered Oct 24, 2020 at 11: 41 faruk13 1, 346 1 1 gold badge 16 16 silver badges 24 24 bronze badges Add a comment | 6 With lodash, \n\n```\ntake\n```\n\n function, you can achieve this by following: \n\n```\n_.take([1, 2, 3]);\n// => [1]\n_.take([1, 2, 3], 2);\n// => [1, 2]\n_.take([1, 2, 3], 5);\n// => [1, 2, 3]\n_.take([1, 2, 3], 0);\n// => []\n```\n\n Share Improve this answer Follow answered Jan 14, 2021 at 13: 14 nurgasemetey 770 3 3 gold badges 16 16 silver badges 40 40 bronze badges Add a comment | 3 The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. \n\n```\nconst animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];\nconsole.log(animals.slice(2));\n// expected output: Array [\"camel\", \"duck\", \"elephant\"]\nconsole.log(animals.slice(2, 4));\n// expected output: Array [\"camel\", \"duck\"]\nconsole.log(animals.slice(1, 5));\n// expected output: Array [\"bison\", \"camel\", \"duck\", \"elephant\"]\nconsole.log(animals.slice(-2));\n// expected output: Array [\"duck\", \"elephant\"]\nconsole.log(animals.slice(2, -1));\n// expected output: Array [\"camel\", \"duck\"]\n```\n\n know more Share Improve this answer Follow answered Aug 30, 2021 at 22: 39 MD SHAYON MD SHAYON 8, 109 54 54 silver badges 43 43 bronze badges Add a comment | 0 With LInQer you can do: \n\n```\nEnumerable.from(list).take(3).toArray();\n```\n\n Share Improve this answer Follow edited Oct 16, 2020 at 10: 20 Penny Liu 17. 9k 5 5 gold badges 88 88 silver badges 109 109 bronze badges answered Jan 6, 2020 at 16: 27 Siderite Zackwehdex Siderite Zackwehdex 6, 630 3 3 gold badges 33 33 silver badges 49 49 bronze badges Add a comment | Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript arrays filtering slice extract See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Visit chat Linked 10 Javascript Array - get first 10 items 0 how can i have the first 3 elements of an array of variable length in Javascript 0 How to loop through some items in an array in React JSX 0 Limit JSON results in array 0 Loop through first 3 item in array JavaScript(react) -4 How to use slice JS in array 0 How to use for-loop in map in React 0 How can I get 10 selected ID`s from objectIDs? 0 Javascript. filter all items with index less than certain value 0 How to get the next element from an array for a given subarray See more linked questions Related 12210 How can I remove a specific item from an array in JavaScript? 7577 How do I remove a property from a JavaScript object? 4342 How to insert an item into an array at a specific index? 4995 How do I check if an array includes a value in JavaScript? 4127 Create ArrayList from array 6740 How do I return the response from an asynchronous call? 5391 How do I make the first letter of a string uppercase in JavaScript? 2426 How can I add new array elements at the beginning of an array in JavaScript? 4923 How do I get a timestamp in JavaScript? Hot Network Questions In \"Little Women\" (1949), what is the German song sung and played on the piano by Professor Bhaer? \"drop\" as arrival What kind of bug is this? Why is no flickering observed in polarized filters? How to approach untraceable citation How do I know if my tubeless-ready tire is seated properly? Did the Apollo Command Module launch with the docking probe already in place? Using a digital potentiometer compared to 'real resistors' for variable gain audio amplifier Uniform convergence of metrics imply that induced topologies are equal and possible error in Burago, Ivanov's \"A Course in Metric Geometry\" What are the biblical arguments against the idea of a post-mortem opportunity for salvation? Does Jesus' statement in Luke 21: 19 indicate that Stephen acted without the wisdom he should have received? Does Innate Sorcery grant Advantage to True Strike? Would this weapon be good for catching melee weapons? Naming of parent keys and their modes A question on the paper \"Maximal unramified extensions of imaginary quadratic number fields of small conductors\" Meaning of '#' suffix on SQL Server columns What is the measure of the new angle? How can R and its associate software be distributed (incompatible LGPL 2. 1 and Apache 2) Dividing both the interior and the boundary of a square into equal parts using polyominos 90-00s TV show. Colony established on a habitable planet. Colony is surrounded by a large wall. Expedition outside the wall encounter exiled group How to find \"minimal polynomial\" of a rational number? Can I say \"inbound/outbound trips/journeys/visits to/from somewhere\"? How to show that the complement of an Archimedean spiral is open and connected? Keep two entire Linux desktop systems in sync more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.2,
- "coherence_score": 7.0,
- "word_count": 2714,
- "timestamp": "2025-09-03 07:33:04"
- }
- },
- {
- "id": "5df261ceeacf",
- "url": "https://stackoverflow.com/questions/46169472/what-is-the-difference-between-using-js-vs-jsx-files-in-react",
- "title": "reactjs - What is the difference between using .js vs .jsx files in React? - Stack Overflow",
- "content": "What is the difference between using. js vs. jsx files in React? Ask Question Asked 7 years, 11 months ago Modified 10 months ago Viewed 424k times 630 There is something I find very confusing when working in React. There are plenty of examples available on internet which use. js files with react but many others use. jsx files. I have read about. jsx files and my understanding is that they just let you write HTML tags within JavaScript. But the same thing can be written in. js files as well. So what is the actual difference between using these two file types in React? reactjs jsx Share Improve this question Follow edited Oct 11, 2024 at 15: 44 TylerH 21. 2k 82 82 gold badges 81 81 silver badges 119 119 bronze badges asked Sep 12, 2017 at 6: 34 ConfusedDeveloper 7, 071 5 5 gold badges 23 23 silver badges 42 42 bronze badges 1 3 It doesn't make any difference, but, if you're an adept to clean code you can follow the Airbnb Coding Style, which recommend using. jsx github. com/airbnb/javascript/tree/master/react#basic-rules James Bissick – James Bissick 04/06/2021 11: 00: 06 Commented Apr 6, 2021 at 11: 00 Add a comment | 12 Answers 12 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 468 There is none when it comes to file extensions. Your bundler/transpiler/whatever takes care of resolving what type of file contents there is. There are however some other considerations when deciding what to put into a \n\n```\n.js\n```\n\n or a \n\n```\n.jsx\n```\n\n file type. Since JSX isn't standard JavaScript one could argue that anything that is not \"plain\" JavaScript should go into its own extensions ie., \n\n```\n.jsx\n```\n\n for JSX and \n\n```\n.ts\n```\n\n for TypeScript for example. There's a good discussion here available for read Share Improve this answer Follow answered Sep 12, 2017 at 6: 36 Henrik Andersson Henrik Andersson 47. 4k 16 16 gold badges 101 101 silver badges 94 94 bronze badges 3 14 Nice link! For me this discussion is something also interesting! Felipe Augusto – Felipe Augusto 07/11/2018 21: 26: 23 Commented Jul 11, 2018 at 21: 26 9 Well said. JSX is neither JS or HTML, so giving it its own extension helps indicate what it is--even if using \n\n```\n.jsx\n```\n\n isn't a requirement STW – STW 11/08/2019 00: 47: 25 Commented Nov 8, 2019 at 0: 47 6 The distinction between. js and. jsx files was useful before Babel, but it’s not that useful anymore. mercury – mercury 03/31/2021 06: 48: 00 Commented Mar 31, 2021 at 6: 48 Add a comment | 109 In most of the cases it’s only a need for the transpiler/bundler, which might not be configured to work with JSX files, but with JS! So you are forced to use JS files instead of JSX. And since react is just a library for javascript, it makes no difference for you to choose between JSX or JS. They’re completely interchangeable! In some cases users/developers might also choose JSX over JS, because of code highlighting, but the most of the newer editors are also viewing the react syntax correctly in JS files. Share Improve this answer Follow edited Jan 30, 2018 at 16: 25 answered Sep 12, 2017 at 6: 43 marpme 2, 435 1 1 gold badge 17 17 silver badges 23 23 bronze badges Add a comment | 69 JSX tags ( \n\n```\n\n```\n\n ) are clearly not standard javascript and have no special meaning if you put them inside a naked \n\n```\n\n\n\n\n```\n\n inside a module: \n\n```\nconst { jQuery: $, Underscore: _, etc } = window;\n```\n\n Share Improve this answer Follow edited Sep 30, 2017 at 7: 03 answered Sep 30, 2017 at 5: 59 frdnrdb 61 8 8 bronze badges Add a comment | 2 The best solution I've found was: https: //github. com/angular/angular-cli/issues/5139#issuecomment-283634059 Basically, you need to include a dummy variable on typings. d. ts, remove any \"import * as $ from 'jquery\" from your code, and then manually add a tag to jQuery script to your SPA html. This way, webpack won't be in your way, and you should be able to access the same global jQuery variable in all your scripts. Share Improve this answer Follow answered May 23, 2017 at 18: 55 Fabricio 543 1 1 gold badge 6 6 silver badges 21 21 bronze badges Add a comment | 2 This works for me on the webpack. config. js \n\n```\nnew webpack.ProvidePlugin({\n $: 'jquery',\n jQuery: 'jquery',\n 'window.jQuery': 'jquery'\n }),\n```\n\n in another javascript or into HTML add: \n\n```\nglobal.jQuery = require('jquery');\n```\n\n Share Improve this answer Follow edited Nov 20, 2017 at 22: 19 answered Nov 16, 2017 at 15: 15 JPRLCol 200 12 12 silver badges 30 30 bronze badges Add a comment | 0 Whoever is facing any issues after applying the good solutions found here, all you need is simply follow the clear instruction inside the webpack. config. js file: \n\n```\n// uncomment if you're having problems with a jQuery plugin\n.autoProvidejQuery()\n```\n\n By un-commenting this line, you will get things work well! Share Improve this answer Follow answered Jan 5, 2023 at 14: 28 Yazid Erman Yazid Erman 1, 186 1 1 gold badge 13 13 silver badges 25 25 bronze badges Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript jquery amd webpack See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 1 Loading jQuery plugins with webpack, gulp, and typescript 180 configuration. module has an unknown property 'loaders' 88 Webpack ProvidePlugin vs externals? 43 'jquery is not defined' when using webpack to load bootstrap 28 Webpack and External Libs: ProvidePlugin vs entry vs global import? 16 Exposing jquery plugin with Webpack 16 JQuery Plugin (datatables) with Webpack and Typescript 13 How to import jquery in webpack 13 Uncaught ReferenceError: $ is not defined Webpack and embedded script 4 __WEBPACK_IMPORTED_MODULE_5_jquery__(. . . ). modal is not a function See more linked questions Related 2 How to make \"require('jquery')\" automatically load with many jquery plugins/extensions in webpack? 1 Webpack modules dependencies like in requirejs 0 webpack, how to manage dependencies 6 Add Dependency in Webpack Plugin 4 Loading jQuery plugins with webpack 2 3 Require a jQuery-Plugin with Webpack 12 How to use jQuery dependant plugins in create-react-app 11 Including additional jQuery plugins globally with Webpack 4 3 Controlling dependencies in Webpack 1 Is it possible to exclude jquery from jquery dependent plugins in bundle? Hot Network Questions How can R and its associate software be distributed (incompatible LGPL 2. 1 and Apache 2) What is the measure of the new angle? c++ format_to verbosity What should an airline pilot do in a decompression with a MEA of FL200? Which version of Amos 6: 12 is closest to the original? The sum of an irreducible representation over a subset of a finite group. PF2e: Raising a shield out of combat How does one get more oxyfern? Uniform convergence of metrics imply that induced topologies are equal and possible error in Burago, Ivanov's \"A Course in Metric Geometry\" How can I attach the bottom of a window A. C. unit to the bottom of a window? Did the Apollo Command Module launch with the docking probe already in place? Looking for a short story collection, history of the universe starting with the big bang Why did Hashem try killing Moses on his way to Egypt? Minimal C++ Coroutine Scheduler with Sleep, Spawn, and Join Support What is an appropriate automatic tool for bolts? Can I say \"inbound/outbound trips/journeys/visits to/from somewhere\"? Naming of parent keys and their modes How to sync Thunderbird emails, over two computers? What did Jesus eat in relationship to his Jewish culture and tradition? Alternative proofs that two bases of a vector space have the same size Comparative law: Does a lease transfer all benefits at once or gradually? Protecting against GPS jamming via directional antenna Why does MathML display differentiation operator weirdly when using ⅆ ? How to write \"the positive sign is replaced by negative sign and negative sign by positive sign\"? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.2,
- "coherence_score": 7.0,
- "word_count": 3783,
- "timestamp": "2025-09-03 07:33:05"
- }
- },
- {
- "id": "92e73d896612",
- "url": "https://stackoverflow.com/questions/52100103/getting-all-documents-from-one-collection-in-firestore",
- "title": "javascript - Getting all documents from one collection in Firestore - Stack Overflow",
- "content": "Getting all documents from one collection in Firestore Ask Question Asked 7 years ago Modified 1 year, 6 months ago Viewed 291k times Part of Google Cloud Collective 152 Hi I'm starting with javascript and react-native and I'm trying to figure out this problem for hours now. Can someone explain me how to get all the documents from firestore collection? I have been trying this: \n\n```\nasync getMarkers() {\n const events = await firebase.firestore().collection('events').get()\n .then(querySnapshot => {\n querySnapshot.docs.map(doc => {\n console.log('LOG 1', doc.data());\n return doc.data();\n });\n });\n console.log('LOG 2', events);\n return events;\n}\n```\n\n Log 1 prints all the objects(one by one) but log 2 is undefined, why? javascript firebase react-native google-cloud-firestore Share Improve this question Follow asked Aug 30, 2018 at 14: 58 Stroi 1, 961 3 3 gold badges 14 14 silver badges 17 17 bronze badges Add a comment | 14 Answers 14 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 288 The example in the other answer is unnecessarily complex. This would be more straightforward, if all you want to do is return the raw data objects for each document in a query or collection: \n\n```\nasync getMarker() {\n const snapshot = await firebase.firestore().collection('events').get()\n return snapshot.docs.map(doc => doc.data());\n}\n```\n\n Share Improve this answer Follow answered Aug 30, 2018 at 16: 40 Doug Stevenson Doug Stevenson 320k 37 37 gold badges 457 457 silver badges 473 473 bronze badges 12 this worked for me \n\n```\nconst snapshot = await firestore.collection('events').get()\n```\n\n etoxin – etoxin 07/08/2019 11: 35: 44 Commented Jul 8, 2019 at 11: 35 4 @etoxin That would work only if your imports/requires were different than what the OP was doing. Doug Stevenson – Doug Stevenson 07/08/2019 11: 36: 55 Commented Jul 8, 2019 at 11: 36 Would this count towards one read for the quota, or would each document in the collection count as a read operation? Mentor – Mentor 07/22/2019 18: 50: 16 Commented Jul 22, 2019 at 18: 50 3 @Mentor The query will incur a read for every matched document, regardless of what you do with the snapshots in your code. Doug Stevenson – Doug Stevenson 07/22/2019 19: 19: 58 Commented Jul 22, 2019 at 19: 19 2 @bermick one query is one round trip. The entire results of the query come back in the snapshot. Doug Stevenson – Doug Stevenson 05/21/2020 19: 12: 16 Commented May 21, 2020 at 19: 12 | Show 7 more comments 37 if you want include Id \n\n```\nasync getMarkers() {\n const events = await firebase.firestore().collection('events')\n events.get().then((querySnapshot) => {\n const tempDoc = querySnapshot.docs.map((doc) => {\n return { id: doc.id, ...doc.data() }\n })\n console.log(tempDoc)\n })\n}\n```\n\n Same way with array \n\n```\nasync getMarkers() {\n const events = await firebase.firestore().collection('events')\n events.get().then((querySnapshot) => {\n const tempDoc = []\n querySnapshot.forEach((doc) => {\n tempDoc.push({ id: doc.id, ...doc.data() })\n })\n console.log(tempDoc)\n })\n }\n```\n\n Share Improve this answer Follow answered Oct 21, 2019 at 21: 11 IMANULLAH 579 5 5 silver badges 2 2 bronze badges Add a comment | 13 I made it work this way: \n\n```\nasync getMarkers() {\n const markers = [];\n await firebase.firestore().collection('events').get()\n .then(querySnapshot => {\n querySnapshot.docs.forEach(doc => {\n markers.push(doc.data());\n });\n });\n return markers;\n}\n```\n\n Share Improve this answer Follow answered Aug 30, 2018 at 15: 45 Stroi 1, 961 3 3 gold badges 14 14 silver badges 17 17 bronze badges 0 Add a comment | 11 if you need to include the key of the document in the response, another alternative is: \n\n```\nasync getMarker() {\n const snapshot = await firebase.firestore().collection('events').get()\n const documents = [];\n snapshot.forEach(doc => {\n const document = { [doc.id]: doc.data() };\n documents.push(document);\n }\n return documents;\n}\n```\n\n Share Improve this answer Follow edited Feb 25, 2022 at 15: 15 OneHoopyFrood 3, 989 3 3 gold badges 27 27 silver badges 39 39 bronze badges answered Jun 29, 2019 at 21: 10 Rodrigo 382 5 5 silver badges 13 13 bronze badges 0 Add a comment | 10 The docs state: \n\n```\nimport { collection, getDocs } from \"firebase/firestore\";\nconst querySnapshot = await getDocs(collection(db, \"cities\"));\nquerySnapshot.forEach((doc) => {\n // doc.data() is never undefined for query doc snapshots\n console.log(doc.id, \" => \", doc.data());\n});\n```\n\n However I am using the following (excuse the TypeScript): \n\n```\nimport { collection, Firestore, getDocs, Query, QueryDocumentSnapshot, QuerySnapshot } from 'firebase/firestore'\nconst q: Query = collection(db, 'videos')\nconst querySnapshot: QuerySnapshot = await getDocs(q)\nconst docs: QueryDocumentSnapshot[] = querySnapshot.docs\nconst videos: IVideoProcessed[] = docs.map((doc: QueryDocumentSnapshot) => doc.data())\n```\n\n where db has the type \n\n```\nFirestore\n```\n\n Share Improve this answer Follow answered Jan 7, 2022 at 2: 58 danday74 57. 9k 56 56 gold badges 271 271 silver badges 336 336 bronze badges Add a comment | 7 You could get the whole collection as an object, rather than array like this: \n\n```\nasync function getMarker() {\n const snapshot = await firebase.firestore().collection('events').get()\n const collection = {};\n snapshot.forEach(doc => {\n collection[doc.id] = doc.data();\n });\n return collection;\n}\n```\n\n That would give you a better representation of what's in firestore. Nothing wrong with an array, just another option. Share Improve this answer Follow edited Jul 20, 2022 at 6: 05 Wizard 533 1 1 gold badge 8 8 silver badges 16 16 bronze badges answered Oct 11, 2019 at 18: 56 OneHoopyFrood 3, 989 3 3 gold badges 27 27 silver badges 39 39 bronze badges Add a comment | 3 Two years late but I just began reading the Firestore documentation recently cover to cover for fun and found \n\n```\nwithConverter\n```\n\n which I saw wasn't posted in any of the above answers. Thus: If you want to include ids and also use \n\n```\nwithConverter\n```\n\n (Firestore's version of ORMs, like ActiveRecord for Ruby on Rails, Entity Framework for. NET, etc), then this might be useful for you: Somewhere in your project, you probably have your \n\n```\nEvent\n```\n\n model properly defined. For example, something like: Your model (in \n\n```\nTypeScript\n```\n\n ): \n\n```\n./models/Event.js\n```\n\n \n\n```\nexport class Event {\n constructor (\n public id: string,\n public title: string,\n public datetime: Date\n )\n}\nexport const eventConverter = {\n toFirestore: function (event: Event) {\n return {\n // id: event.id, // Note! Not in \".data()\" of the model!\n title: event.title,\n datetime: event.datetime\n }\n },\n fromFirestore: function (snapshot: any, options: any) {\n const data = snapshot.data(options)\n const id = snapshot.id\n return new Event(id, data.title, data.datetime)\n }\n}\n```\n\n And then your client-side \n\n```\nTypeScript\n```\n\n code: \n\n```\nimport { eventConverter } from './models/Event.js'\n...\nasync function loadEvents () {\n const qs = await firebase.firestore().collection('events')\n .orderBy('datetime').limit(3) // Remember to limit return sizes!\n .withConverter(eventConverter).get()\n const events = qs.docs.map((doc: any) => doc.data())\n ...\n}\n```\n\n Two interesting quirks of Firestore to notice (or at least, I thought were interesting): Your \n\n```\nevent.id\n```\n\n is actually stored \"one-level-up\" in \n\n```\nsnapshot.id\n```\n\n and not \n\n```\nsnapshot.data()\n```\n\n. If you're using TypeScript, the TS linter (or whatever it's called) sadly isn't smart enough to understand: \n\n```\nconst events = qs.docs.map((doc: Event) => doc.data())\n```\n\n even though right above it you explicitly stated: \n\n```\n.withConverter(eventConverter)\n```\n\n Which is why it needs to be \n\n```\ndoc: any\n```\n\n. ( But! You will actually get \n\n```\nArray\n```\n\n back! (Not \n\n```\nArray
\n```\n\n And this is my package. json file in which you can see that everything is there. \n\n```\n\"name\": \"frontend\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"dependencies\": {\n \"@testing-library/jest-dom\": \"^5.11.4\",\n \"@testing-library/react\": \"^11.1.0\",\n \"@testing-library/user-event\": \"^12.1.10\",\n \"@types/jest\": \"^26.0.15\",\n \"@types/node\": \"^12.0.0\",\n \"@types/react\": \"^17.0.0\",\n \"@types/react-dom\": \"^17.0.0\",\n \"@types/react-router-dom\": \"^5.3.2\",\n \"react\": \"^17.0.2\",\n \"react-dom\": \"^17.0.2\",\n \"react-router-dom\": \"^6.0.1\",\n \"react-scripts\": \"4.0.3\",\n \"typescript\": \"^4.1.2\",\n \"web-vitals\": \"^1.0.1\"\n },\n \"scripts\": {\n \"start\": \"react-scripts start\",\n \"build\": \"react-scripts build\",\n \"test\": \"react-scripts test\",\n \"eject\": \"react-scripts eject\"\n },\n \"eslintConfig\": {\n \"extends\": [\n \"react-app\",\n \"react-app/jest\"\n ]\n },\n \"browserslist\": {\n \"production\": [\n \">0.2%\",\n \"not dead\",\n \"not op_mini all\"\n ],\n \"development\": [\n \"last 1 chrome version\",\n \"last 1 firefox version\",\n \"last 1 safari version\"\n ]\n }\n}\n```\n\n reactjs typescript react-router react-router-dom Share Improve this question Follow edited Nov 11, 2021 at 12: 08 Veselin Kontić asked Nov 6, 2021 at 18: 04 Veselin Kontić Veselin Kontić 1, 898 2 2 gold badges 15 15 silver badges 26 26 bronze badges 0 Add a comment | 7 Answers 7 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 304 react router v6 doesn't support \n\n```\nexact\n```\n\n anymore. // old - v5 \n\n```\n\n```\n\n // new - v6 \n\n```\n} />\n```\n\n As stated in their documentation: You don't need to use an exact prop on \n\n```\n\n```\n\n anymore. This is because all paths match exactly by default. If you want to match more of the URL because you have child routes use a trailing * as in \n\n```\n\n```\n\n. You can refer to this migration guide: https: //reactrouter. com/en/main/upgrading/v5 Share Improve this answer Follow edited Jan 9, 2023 at 4: 44 Yan Burtovoy 306 1 1 gold badge 3 3 silver badges 16 16 bronze badges answered Nov 6, 2021 at 18: 06 Antonio Pantano Antonio Pantano 5, 082 2 2 gold badges 26 26 silver badges 27 27 bronze badges 2 23 Thank you for pointing this out. Also, kind of frustrating to see such drastic breaking changes without more of a timeline to migrate between v5 and v6. Literally hundreds of files for some folks. jmunsch – jmunsch 12/28/2021 08: 04: 42 Commented Dec 28, 2021 at 8: 04 I don't want exact match, then what to do in v6 as by default it do exact match only Rupal – Rupal 05/13/2024 05: 38: 08 Commented May 13, 2024 at 5: 38 Add a comment | 14 In the case of React Router v6, I add Routes and Route to the import. Example: \n\n```\nimport { BrowserRouter, Route, Routes } from 'react-router-dom';\nimport Home from \"./pages/Home\";\nimport NewRoom from \"./pages/NewRoom\";\nfunction App() {\n return (\n \n \n }/>\n }/>\n \n \n );\n}\nexport default App;\n```\n\n Share Improve this answer Follow edited May 27, 2022 at 21: 51 H3AR7B3A7 5, 331 3 3 gold badges 21 21 silver badges 42 42 bronze badges answered Apr 19, 2022 at 20: 14 nikolas lutgens nikolas lutgens 141 1 1 silver badge 3 3 bronze badges Add a comment | 5 I have been through this same issue, the new React-Router doesn't support the \n\n```\nexact\n```\n\n keyword. You can simply remove it from the and it will work just fine. Also instead of \n\n```\ncomponent\n```\n\n you have to use \n\n```\nelement\n```\n\n and pass the element tag into it. Share Improve this answer Follow answered Nov 11, 2021 at 1: 42 Lucas Gabriel Lucas Gabriel 428 5 5 silver badges 11 11 bronze badges Add a comment | 1 Just replace \n\n```\nexact\n```\n\n with \n\n```\nend\n```\n\n. Rename \n\n```\n\n```\n\n to \n\n```\n\n```\n\n. https: //reactrouter. com/en/v6. 3. 0/upgrading/v5#rename-navlink-exact-to-navlink-end Share Improve this answer Follow answered Nov 14, 2022 at 20: 51 Paul Bornuat Paul Bornuat 11 1 1 bronze badge 1 I have a route going to a 'Create Post' page, with path '/post'. The created posts live on the path '/post/: id'. I didn't want the 'Create Post' NavLink to be selected when the path was '/post/1', so putting 'end' on the 'Create Post' NavLink solved the problem. Naj – Naj 04/10/2024 09: 54: 17 Commented Apr 10, 2024 at 9: 54 Add a comment | 1 The Syntax is changed in \"react-router-dom\" \"@types/react-router-dom\": \"^5. 3. 2\", ===== > \n\n```\nimport {BrowserRouter as Router, Route} from \"react-router-dom\"\n```\n\n \"react-router-dom\": \"^6. 0. 1\", ============ > \n\n```\nimport { BrowserRouter, Routes, Route } from \"react-router-dom\";\n```\n\n Please Updated the syntax \n\n```\n\n \n \n \n \n \n\n```\n\n =============================================================== OR Use the \"element\" in \"Route\" \n\n```\n\n \n \n } />\n } />\n \n\n```\n\n Share Improve this answer Follow answered Dec 14, 2024 at 14: 32 Aju Thomas Kalloor Aju Thomas Kalloor 11 1 1 bronze badge Add a comment | 0 I don't know if this keeps happening to you. But there you have: \n\n```\n\"dependencies\": {\n ...\n \"@types/react-router-dom\": \"^5.3.2\",\n ...\n \"react-router-dom\": \"^6.0.1\",\n ...\n},\n```\n\n And maybe the problem is that the version of your react-router-dom and the types are not the same and give compatibility problems. This library has not been updated yet. The same thing happened to me with a project that I just started. To solve this problem, you can downgrade the version of your react-router-dom to v5 and work under that syntax, or wait for the update of the types and use the most recent version. Keep in mind that there are important changes in v6 and updating when you have a lot of code could be complicated. Likewise, the previous answers are correct, \n\n```\nexact\n```\n\n does not exist in the new v6 of \n\n```\nreact-router\n```\n\n. Here you can see the current version of the types: https: //www. npmjs. com/package/@types/react-router-dom Share Improve this answer Follow answered Nov 13, 2021 at 2: 50 Pkcarreno 1 3 3 bronze badges 1 It's not that the type library hasn't been updated; as of v6, react-router-dom includes its own type declarations and the @types package is no longer needed. DustInComp – DustInComp 11/13/2021 02: 59: 38 Commented Nov 13, 2021 at 2: 59 Add a comment | -3 what worked for me was re-installing the package \n\n```\nnpm install react-router-dom\n```\n\n Share Improve this answer Follow answered Jul 27, 2022 at 21: 18 Mr Coolman Mr Coolman 25 4 4 bronze badges 1 3 The question is: How did you even start creating routes or facing the problem without the any router component installed? DevMinds – DevMinds 11/08/2022 03: 31: 18 Commented Nov 8, 2022 at 3: 31 Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions reactjs typescript react-router react-router-dom See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 122 Switch' is not exported from 'react-router-dom' 2 React 18 router changing url but not component 2 I am having trouble using the EXACT property for my routes, I am using React 18 1 React Router Components not showing -1 Route is not working after upgrading to react-route v6 1 React router v6 children routes not displaying correct component Related 12 react-router-dom TypeScript TS2322: Type 'typeof Index' is not assignable to type 2 Typescript errors with React Router DOM 0 react-router-dom Element Type Invalid 3 react-router-dom Failed prop type: Invalid prop `exact` of type `string` 2 react-router and typescript throwing \"Can't resolve 'react-router-dom'\" error 9 Running into TS error \"Property 'exact' does not exist on type' with react-router\" 3 React Router Dom: Warning: Received `true` for a non-boolean attribute `exact` 2 Typescript React - has no properties in common with type 'IntrinsicAttributes' 1 React router in typescript giving errors 6 Type '{ path: string; element: Element; }' is not assignable to type 'IntrinsicAttributes & BrowserRouterProps' Hot Network Questions Would it be reasonable for a theist to claim that an atheist cannot appeal to any convention or apparatus of logic if there is no foundational agent? What was the first game where your guide/quest giver turned out to be a key antagonist/villain? Keep two entire Linux desktop systems in sync How does the capacitive sensing works on the PC / PC/XT keyboard type 2? Is a condition termed a \"disease\" only when it has a known cause? Does the water content inside food regulate the cooking process? expr \"/foo\": \"/\" gives a syntax error How do I know if my tubeless-ready tire is seated properly? \"seen as X\" - sicut, ablative of means, other? Add Y to X to get a palindrome In \"Little Women\" (1949), what is the German song sung and played on the piano by Professor Bhaer? How can I attach the bottom of a window A. C. unit to the bottom of a window? I thought, Well, I'll take that for my mum because she \"won't have eaten\" vs \"hasn't eaten\" Volume-preserving fluid flows are incompressible. What about surface-area preserving flows? PF2e: Raising a shield out of combat Extra space after \\left…\\right workaround with \\vphantom in LaTeX Conjecture possibly related to Hardy-Littlewood II Knowledge is free, but time costs money? When to use \"tun würde*\" vs. \"täte*\" as the subjunctive II of \"tun\" Does the age limit for U. S. presidents apply at the the time of election or swearing in? need help creating a custom enumerate list that use arabic letters as label If we have no free will, wherein lies the illusion? Looking for a short story collection, history of the universe starting with the big bang Alternative proofs that two bases of a vector space have the same size more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.2,
- "coherence_score": 7.0,
- "word_count": 1914,
- "timestamp": "2025-09-03 07:33:17"
- }
- },
- {
- "id": "4949d026a054",
- "url": "https://javascript.info/",
- "title": "The Modern JavaScript Tutorial",
- "content": "The JavaScript language Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP. We concentrate on the language itself here, with the minimum of environment-specific notes. An introduction An Introduction to JavaScript Manuals and specifications Code editors Developer console JavaScript Fundamentals Hello, world! Code structure The modern mode, \"use strict\" Variables Data types Interaction: alert, prompt, confirm Type Conversions Basic operators, maths Comparisons Conditional branching: if, '? ' Logical operators Nullish coalescing operator '? ? ' Loops: while and for The \"switch\" statement Functions Function expressions Arrow functions, the basics JavaScript specials More… Code quality Debugging in the browser Coding Style Comments Ninja code Automated testing with Mocha Polyfills and transpilers Objects: the basics Objects Object references and copying Garbage collection Object methods, \"this\" Constructor, operator \"new\" Optional chaining '? . ' Symbol type Object to primitive conversion Data types Methods of primitives Numbers Strings Arrays Array methods Iterables Map and Set WeakMap and WeakSet Object. keys, values, entries Destructuring assignment Date and time JSON methods, toJSON More… Advanced working with functions Recursion and stack Rest parameters and spread syntax Variable scope, closure The old \"var\" Global object Function object, NFE The \"new Function\" syntax Scheduling: setTimeout and setInterval Decorators and forwarding, call/apply Function binding Arrow functions revisited More… Object properties configuration Property flags and descriptors Property getters and setters Prototypes, inheritance Prototypal inheritance F. prototype Native prototypes Prototype methods, objects without __proto__ Classes Class basic syntax Class inheritance Static properties and methods Private and protected properties and methods Extending built-in classes Class checking: \"instanceof\" Mixins Error handling Error handling, \"try. . . catch\" Custom errors, extending Error Promises, async/await Introduction: callbacks Promise Promises chaining Error handling with promises Promise API Promisification Microtasks Async/await Generators, advanced iteration Generators Async iteration and generators Modules Modules, introduction Export and Import Dynamic imports Miscellaneous Proxy and Reflect Eval: run a code string Currying Reference Type BigInt Unicode, String internals WeakRef and FinalizationRegistry Browser: Document, Events, Interfaces Learning how to manage the browser page: add elements, manipulate their size and position, dynamically create interfaces and interact with the visitor. Document Browser environment, specs DOM tree Walking the DOM Searching: getElement*, querySelector* Node properties: type, tag and contents Attributes and properties Modifying the document Styles and classes Element size and scrolling Window sizes and scrolling Coordinates More… Introduction to Events Introduction to browser events Bubbling and capturing Event delegation Browser default actions Dispatching custom events UI Events Mouse events Moving the mouse: mouseover/out, mouseenter/leave Drag'n'Drop with mouse events Pointer events Keyboard: keydown and keyup Scrolling Forms, controls Form properties and methods Focusing: focus/blur Events: change, input, cut, copy, paste Forms: event and method submit Document and resource loading Page: DOMContentLoaded, load, beforeunload, unload Scripts: async, defer Resource loading: onload and onerror Miscellaneous Mutation observer Selection and Range Event loop: microtasks and macrotasks Additional articles List of extra topics that assume you've covered the first two parts of tutorial. There is no clear hierarchy here, you can read articles in the order you want. Frames and windows Popups and window methods Cross-window communication The clickjacking attack Binary data, files ArrayBuffer, binary arrays TextDecoder and TextEncoder Blob File and FileReader Network requests Fetch FormData Fetch: Download progress Fetch: Abort Fetch: Cross-Origin Requests Fetch API URL objects XMLHttpRequest Resumable file upload Long polling WebSocket Server Sent Events More… Storing data in the browser Cookies, document. cookie LocalStorage, sessionStorage IndexedDB Animation Bezier curve CSS-animations JavaScript animations Web components From the orbital height Custom elements Shadow DOM Template element Shadow DOM slots, composition Shadow DOM styling Shadow DOM and events Regular expressions Patterns and flags Character classes Unicode: flag \"u\" and class \\p{. . . } Anchors: string start ^ and end $ Multiline mode of anchors ^ $, flag \"m\" Word boundary: \\b Escaping, special characters Sets and ranges [. . . ] Quantifiers +, *, ? and {n} Greedy and lazy quantifiers Capturing groups Backreferences in pattern: \\N and \\k Alternation (OR) | Lookahead and lookbehind Catastrophic backtracking Sticky flag \"y\", searching at position Methods of RegExp and String More… Watch for javascript. info updates We do not send advertisements, only relevant stuff. You choose what to receive: Common updates New courses and screencasts, site updates Javascript/DOM/Interfaces course Node. JS course Angular course React. JS course Typescript course Subscribe By signing up to newsletters you agree to the terms of usage. Share Tutorial map Comments read this before commenting… If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting. If you can't understand something in the article – please elaborate. To insert few words of code, use the \n\n```\n\n```\n\n tag, for several lines – wrap them in \n\n```\n
\n```\n\n tag, for more than 10 lines – use a sandbox ( plnkr, jsbin, codepen …)",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.0,
- "coherence_score": 7.0,
- "word_count": 805,
- "timestamp": "2025-09-03 07:32:47"
- }
- },
- {
- "id": "624b358728c1",
- "url": "https://egghead.io/q/react",
- "title": "In-Depth React Tutorials for 2025 | egghead.io",
- "content": "Most Popular Highest Rated Recently Added Most Watched Level up at React Beginner Just starting out with React course The Beginner's Guide to React course by Kent C. Dodds course Develop Accessible Web Apps with React course by Erin Doyle course Build Maps with React Leaflet course by Colby Fayock Intermediate Hitting your stride course Shareable Custom Hooks in React course by Joe Previte course Simplify React Apps with React Hooks course by Kent C. Dodds course Reusable State and Effects with React Hooks course by Elijah Manor Advanced Above and beyond course Apply Redux to a Modern React Hooks Application course by Jamund Ferguson course Build an App with React Suspense course by Michael Chan course Sync State Across Components with Recoil in React course by Tomasz Łakomy State Management in React When it comes down to it, nearly every UI problem is a state management problem. Orchestrating a whole symphony of menus, forms, and data requests is hard enough before you even begin debating which of the 99 React state management libraries you should pick. We've spoken to top experts in the field of state management to hear their thoughts on why the best ideas in state management aren't always the newest, why principles are often universal where implementations are not, and how state management concepts carry across frameworks and tools. course React State Management Expert Interviews course by Joel Hooks course Introduction to State Machines Using XState course by Kyle Shevlin course Construct Sturdy UIs with XState course by Isaac Mann course React Context for State Management course by Dave Ceddia course Manage Complex Tic Tac Toe Game State in React course by Kyle Shevlin course Manage Application State with Jotai Atoms course by Daishi Kato course Sync State Across Components with Recoil in React course by Tomasz Łakomy course Manage React State with Recoil course by Yoni Weisbrod Style React Apps guide Just enough CSS for Modern App Development Building user interfaces is an essential skill for every web developer to continue to level up in. It’s a core skill. . . landing-page by egghead course Animate React Apps with Framer Motion Will gives you the knowledge of how to customize your animations in any React application. course by Will Johnson course Style an Application from Start to Finish course by Garth Braithwaite course Styling React Applications with Styled Components course by Sara Vieira course Beautiful and Accessible Drag and Drop with react-beautiful-dnd course by Alex Reardon course The Beginner's Guide to Figma course by Joe Previte Build interesting React Apps course Building an OpenGraph image generation API with Cloudinary, Netlify Functions, and React You will come away from this collection with the ability to ship an API that you can use on any of your sites. course by Chris Biscardi course React Real-Time Messaging with GraphQL using urql and OneGraph course by Ian Jones course Build a Terminal Dashboard with React course by Elijah Manor Mental Models for React Never written a line of React? We've got a curated guide designed to teach you all the fundamentals skills and mental models you'll need to build in React. article Is React. js a framework or a toolkit? article by Joel Hooks article WTF is JSX? article by Hiroko Nishimura collection Just JavaScript collection by Dan Abramov article WTF is React? article by Hiroko Nishimura collection Just JavaScript collection by Dan Abramov article WTF is React? article by Hiroko Nishimura article Is React. js a framework or a toolkit? article by Joel Hooks article WTF is JSX? article by Hiroko Nishimura Conversations with React Experts podcast Brian Vaughn, React Core Team podcast by Joel Hooks podcast Ryan Florence Talks About Bringing Web 1. 0 Philosophies Back With Remix podcast by Joel Hooks podcast Kent C. Dodds Chats About How Epic React was Designed for Learner Success podcast by Joel Hooks podcast Jason Lengstorf on GatsbyJS podcast by Joel Hooks Presentations from React Experts talk Drawing the Invisible: React Explained in Five Visual Metaphors talk by Maggie Appleton talk Concurrent React from Scratch talk by Shawn Wang talk Setting Up Feature Flags with React talk by Talia Nassi talk Accessibility-flavored React Components make your Design System Delicious talk by Kathleen McMahon 1, 606 results found for \" * \" Search Results lesson WTF is Tanstack Router lesson by Tomasz Ducin course Build a Real-time Next. js 14 Chat App with Fauna course by Shadid Haque lesson Implement Fauna Signin with Next. js Server Actions and useFormState React Hook lesson by Shadid Haque lesson Stream Chat Messages in Real-time in Next. js from Fauna lesson by Shadid Haque lesson Create and Display Messages using Fauna within a Room in Next. js lesson by Shadid Haque lesson List Available Chat Rooms in Real-time in Next. js from Fauna lesson by Shadid Haque lesson Implement a server-side pagination using React Query lesson by Tomasz Ducin lesson Use Type Narrowing without early function returns with React Query lesson by Tomasz Ducin lesson Implement a server-side search using React Query lesson by Tomasz Ducin lesson Implement a client-side search using React Query lesson by Tomasz Ducin lesson Configure gcTime (garbage collection) within React Query lesson by Tomasz Ducin lesson Configure staleTime within React Query lesson by Tomasz Ducin lesson Manipulate existing queries with React Query Devtools lesson by Tomasz Ducin lesson Implement Parallel Queries execution using multiple useQuery hooks within React Query lesson by Tomasz Ducin lesson Share fetched state across multiple components using React Query lesson by Tomasz Ducin lesson Reuse Query Settings using the queryOptions API lesson by Tomasz Ducin lesson Extract React Query useQuery into custom hooks lesson by Tomasz Ducin lesson Use isPending, isLoading and isFetching flags with React Query lesson by Tomasz Ducin lesson Display loading, error and successful query state using React Query Type Narrowing lesson by Tomasz Ducin lesson Use fetch, axios, ky, or any other promise-based library within useQuery hook lesson by Tomasz Ducin lesson Configure React Query Devtools and inspect existing queries lesson by Tomasz Ducin",
- "metadata": {
- "source_type": "general",
- "quality_score": 9.0,
- "coherence_score": 6.0,
- "word_count": 1002,
- "timestamp": "2025-09-03 07:32:48"
- }
- },
- {
- "id": "a709aaa543b4",
- "url": "https://dev.to/",
- "title": "DEV Community",
- "content": "Auggie CLI is Now Available to Everyone! 🚀 Emma Webb Emma Webb Emma Webb Follow for Augment Code Sep 2 Auggie CLI is Now Available to Everyone! 🚀 # ai # webdev # cli # programming 118 reactions Comments 2 comments 2 min read Top 7 Featured DEV Posts of the Week dev. to staff dev. to staff dev. to staff Follow for The DEV Team Sep 2 Top 7 Featured DEV Posts of the Week # discuss # top7 15 reactions Comments 6 comments 2 min read Meme Monday Ben Halpern Ben Halpern Ben Halpern Follow Sep 1 Meme Monday # discuss # jokes # watercooler 52 reactions Comments 85 comments 1 min read 🖌️ Contrastly — Instantly Check Tailwind Colors Against WCAG AA/AAA Yoko Follow Sep 2 🖌️ Contrastly — Instantly Check Tailwind Colors Against WCAG AA/AAA # tailwindcss # a11y # frontend # webdev 18 reactions Comments 4 comments 1 min read A Love Letter to Vercel! Mahdi Jazini Mahdi Jazini Mahdi Jazini Follow Sep 2 A Love Letter to Vercel! # vercel # nextjs # webdev # programming 36 reactions Comments 17 comments 3 min read Introducing: @traversable/zod andrew jarrett andrew jarrett andrew jarrett Follow Sep 2 Introducing: @traversable/zod # typescript # javascript # opensource # webdev 12 reactions Comments 4 comments 3 min read 💻The HTML of AI: Why Prompting Isn't Enough! Mak Sò Mak Sò Mak Sò Follow Sep 2 💻The HTML of AI: Why Prompting Isn't Enough! # ai # machinelearning # programming # promptengineering 10 reactions Comments Add Comment 4 min read 🚀 Building Stock Sage: Kiro + MCP = Smarter Stock Analysis Aman Wadgaonkar Aman Wadgaonkar Aman Wadgaonkar Follow Sep 2 🚀 Building Stock Sage: Kiro + MCP = Smarter Stock Analysis # kiro # ai # mcp # stocksage 6 reactions Comments Add Comment 3 min read I Hate Dark Mode! ! ! ! ! ! ! Muhammed Sabith Muhammed Sabith Muhammed Sabith Follow Sep 2 I Hate Dark Mode! ! ! ! ! ! ! # discuss # webdev # javascript # tailwindcss 17 reactions Comments 6 comments 1 min read What No One Tells You About TinyGo: Running Go on an Arduino Changed How I Think About Embedded Programming Yevhen Kozachenko 🇺🇦 Yevhen Kozachenko 🇺🇦 Yevhen Kozachenko 🇺🇦 Follow Sep 2 What No One Tells You About TinyGo: Running Go on an Arduino Changed How I Think About Embedded Programming # tinygo # embedprogramming # go # microcontroller 8 reactions Comments Add Comment 4 min read Fargate + Lambda are better together Daniele Frasca Daniele Frasca Daniele Frasca Follow for AWS Community Builders Sep 3 Fargate + Lambda are better together Comments Add Comment 4 min read Cache Me If You Can: Design Patterns for Performance Sibasish Mohanty Sibasish Mohanty Sibasish Mohanty Follow Sep 3 Cache Me If You Can: Design Patterns for Performance # systemdesign # interview # performance # programming Comments Add Comment 2 min read Daily DSA and System Design Journal - 5 I. K I. K I. K Follow Sep 2 Daily DSA and System Design Journal - 5 # systemdesign # beginners # devjournal # dsa 5 reactions Comments Add Comment 3 min read ChatGPT Safety: Parental Controls, GPT-5 Routing, and Crisis Handling Ali Farhat Ali Farhat Ali Farhat Follow Sep 2 ChatGPT Safety: Parental Controls, GPT-5 Routing, and Crisis Handling # chatgpt # gpt5 # apigateway # crisis 23 reactions Comments 3 comments 4 min read 🚀 Day 3 of My DevOps Journey: Git & GitHub for DevOps (From Zero to Daily Workflow) Bhaskar Sharma Bhaskar Sharma Bhaskar Sharma Follow Sep 3 🚀 Day 3 of My DevOps Journey: Git & GitHub for DevOps (From Zero to Daily Workflow) Comments Add Comment 3 min read Practical Patterns for Adding Language Understanding to Any Software System Stanislav Komarovsky Stanislav Komarovsky Stanislav Komarovsky Follow Sep 3 Practical Patterns for Adding Language Understanding to Any Software System # ai # architecture # llm # nlp Comments Add Comment 6 min read Automating Publisher Reporting on AWS: A Serverless Architecture with Slack Alerts Gurudev Prasad Teketi Gurudev Prasad Teketi Gurudev Prasad Teketi Follow Sep 3 Automating Publisher Reporting on AWS: A Serverless Architecture with Slack Alerts Comments Add Comment 3 min read Building Your First RAG System with Amazon Bedrock Agents and FAISS: A Developer's Journey Carlos Cortez 🇵🇪 [AWS Hero] Carlos Cortez 🇵🇪 [AWS Hero] Carlos Cortez 🇵🇪 [AWS Hero] Follow for AWS Heroes Sep 3 Building Your First RAG System with Amazon Bedrock Agents and FAISS: A Developer's Journey # programming # ai # python # aws Comments Add Comment 7 min read Day 13 – Multi-agent Chaos in AI Pipelines (ProblemMap No. 13) PSBigBig Follow Sep 3 Day 13 – Multi-agent Chaos in AI Pipelines (ProblemMap No. 13) # webdev # programming # ai # tutorial Comments Add Comment 3 min read The Art of Beautiful Functions in TypeScript Tareq Hossain Tareq Hossain Tareq Hossain Follow Sep 3 The Art of Beautiful Functions in TypeScript # typescript # functions # programming # cleancode Comments Add Comment 6 min read Svelte Reactivity Explained: How Your UI Updates Automatically Ali Aslam Ali Aslam Ali Aslam Follow Sep 3 Svelte Reactivity Explained: How Your UI Updates Automatically # svelte # javascript # sveltekit # performance Comments Add Comment 18 min read Daily DSA and System Design Journal - 4 I. K I. K I. K Follow Sep 1 Daily DSA and System Design Journal - 4 # dsa # systemdesign # beginners # devjournal 6 reactions Comments 1 comment 3 min read Lessons from Building a Global AI Brand from Scratch Jaideep Parashar Jaideep Parashar Jaideep Parashar Follow Sep 3 Lessons from Building a Global AI Brand from Scratch # ai # startup # learning # beginners 15 reactions Comments 1 comment 2 min read Optimize Your Go Code: Mastering `string` and `[]byte` Conversions Jones Charles Jones Charles Jones Charles Follow Sep 3 Optimize Your Go Code: Mastering `string` and `[]byte` Conversions # go # programming # performance # webdev Comments Add Comment 13 min read You May Need an Anti-Corruption Layer Jesse Warden Jesse Warden Jesse Warden Follow Sep 3 You May Need an Anti-Corruption Layer # typescript # architecture Comments Add Comment 4 min read loading. . .",
- "metadata": {
- "source_type": "blog",
- "quality_score": 9.0,
- "coherence_score": 6.0,
- "word_count": 1044,
- "timestamp": "2025-09-03 07:32:56"
- }
- },
- {
- "id": "f3e141963d3b",
- "url": "https://github.com/facebook/react",
- "title": "GitHub - facebook/react: The library for web and native user interfaces.",
- "content": "facebook / react Public Notifications You must be signed in to change notification settings Fork 49. 2k Star 239k The library for web and native user interfaces. react. dev License MIT license 239k stars 49. 2k forks Branches Tags Activity Star Notifications You must be signed in to change notification settings facebook/react main Branches Tags Go to file Code Open more actions menu Folders and files Name Last commit message Last commit date Latest commit History 20, 817 Commits. codesandbox. github. github compiler fixtures flow-typed packages scripts scripts. editorconfig. eslintignore. eslintrc. js. eslintrc. js. git-blame-ignore-revs. gitattributes. gitignore. mailmap. nvmrc. prettierignore. prettierrc. js. prettierrc. js. watchmanconfig. watchmanconfig CHANGELOG. md CHANGELOG. md CODE_OF_CONDUCT. md CODE_OF_CONDUCT. md CONTRIBUTING. md CONTRIBUTING. md LICENSE MAINTAINERS README. md README. md ReactVersions. js ReactVersions. js SECURITY. md SECURITY. md babel. config-react-compiler. js babel. config-react-compiler. js babel. config-ts. js babel. config-ts. js babel. config. js babel. config. js dangerfile. js dangerfile. js flow-typed. config. json flow-typed. config. json package. json package. json react. code-workspace react. code-workspace yarn. lock yarn. lock View all files Repository files navigation React · React is a JavaScript library for building user interfaces. Declarative: React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable, simpler to understand, and easier to debug. Component-Based: Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep the state out of the DOM. Learn Once, Write Anywhere: We don't make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code. React can also render on the server using Node and power mobile apps using React Native. Learn how to use React in your project. Installation React has been designed for gradual adoption from the start, and you can use as little or as much React as you need: Use Quick Start to get a taste of React. Add React to an Existing Project to use as little or as much React as you need. Create a New React App if you're looking for a powerful JavaScript toolchain. Documentation You can find the React documentation on the website. Check out the Getting Started page for a quick overview. The documentation is divided into several sections: Quick Start Tutorial Thinking in React Installation Describing the UI Adding Interactivity Managing State Advanced Guides API Reference Where to Get Support Contributing Guide You can improve it by sending pull requests to this repository. Examples We have several examples on the website. Here is the first one to get you started: \n\n```\nimport { createRoot } from 'react-dom/client';\nfunction HelloMessage({ name }) {\n return
Hello {name}
;\n}\nconst root = createRoot(document.getElementById('container'));\nroot.render();\n```\n\n This example will render \"Hello Taylor\" into a container on the page. You'll notice that we used an HTML-like syntax; we call it JSX. JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. Contributing The main purpose of this repository is to continue evolving React core, making it faster and easier to use. Development of React happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving React. Code of Conduct Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated. Contributing Guide Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to React. Good First Issues To help you get your feet wet and get you familiar with our contribution process, we have a list of good first issues that contain bugs that have a relatively limited scope. This is a great place to get started. License React is MIT licensed. About The library for web and native user interfaces. react. dev Topics react javascript library ui frontend declarative Resources Readme License MIT license Code of conduct Code of conduct Contributing Security policy Security policy Uh oh! There was an error while loading. Please reload this page. Activity Custom properties Stars 239k stars Watchers 6. 7k watching Forks 49. 2k forks Report repository Releases 105 19. 1. 1 (July 28, 2025) Latest Jul 28, 2025 + 104 releases Used by 29. 8m + 29, 751, 318 Contributors 1, 709 + 1, 695 contributors Languages JavaScript 67. 3% TypeScript 29. 1% HTML 1. 5% CSS 1. 1% C++ 0. 6% CoffeeScript 0. 2% Other 0. 2%",
- "metadata": {
- "source_type": "github",
- "quality_score": 9.0,
- "coherence_score": 7.0,
- "word_count": 819,
- "timestamp": "2025-09-03 07:33:00"
- }
- },
- {
- "id": "151dc0f22c07",
- "url": "https://stackoverflow.com/questions/29552601/how-to-set-the-defaultroute-to-another-route-in-react-router",
- "title": "javascript - How to set the DefaultRoute to another Route in React Router - Stack Overflow",
- "content": "How to set the DefaultRoute to another Route in React Router Ask Question Asked 10 years, 4 months ago Modified 7 months ago Viewed 273k times 150 I have the following: \n\n```\n\n \n \n \n \n \n \n \n```\n\n When using the DefaultRoute, SearchDashboard renders incorrectly since any *Dashboard needs to rendered within Dashboard. I would like for my DefaultRoute within the \"app\" Route to point to the Route \"searchDashboard\". Is this something that I can do with React Router, or should I use normal Javascript (for a page redirect) for this? Basically, if the user goes to the home page I want to send them instead to the search dashboard. So I guess I'm looking for a React Router feature equivalent to \n\n```\nwindow.location.replace(\"mygreathostname.com/#/dashboards/searchDashboard\");\n```\n\n javascript routes reactjs http-redirect react-router Share Improve this question Follow edited Apr 16, 2015 at 17: 49 Matthew Herbst asked Apr 10, 2015 at 2: 59 Matthew Herbst Matthew Herbst 32. 3k 27 27 gold badges 92 92 silver badges 139 139 bronze badges 2 1 Have your tried of using Redirect instead of DefaultRoute? Jonatan Lundqvist Medén – Jonatan Lundqvist Medén 04/10/2015 12: 07: 08 Commented Apr 10, 2015 at 12: 07 @JonatanLundqvistMedén that's exactly what I was looking for, thank you! Write it as an answer and I'll mark it as correct. Sorry for the delayed response. Matthew Herbst – Matthew Herbst 04/17/2015 22: 19: 20 Commented Apr 17, 2015 at 22: 19 Add a comment | 19 Answers 19 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 195 You can use Redirect instead of DefaultRoute \n\n```\n\n```\n\n Update 2019-08-09 to avoid problem with refresh use this instead, thanks to Ogglas \n\n```\n\n```\n\n Source: https: //stackoverflow. com/a/43958016/3850405 Share Improve this answer Follow edited Mar 3, 2022 at 8: 18 Ogglas 71. 2k 42 42 gold badges 383 383 silver badges 478 478 bronze badges answered Apr 19, 2015 at 6: 04 Jonatan Lundqvist Medén Jonatan Lundqvist Medén 2, 870 1 1 gold badge 19 19 silver badges 15 15 bronze badges 7 6 is it just me, or when using this to hit a deep url directly, I always get redirected to the \"to\" url, instead of the route I'm trying to hit? Pablote – Pablote 04/17/2017 18: 47: 48 Commented Apr 17, 2017 at 18: 47 Should be noticed that if you are doing some redirection like \n\n```\nfrom='/a' to='/a/:id'\n```\n\n, you will need to use \n\n```\n\n```\n\n to include your \n\n```\n\n```\n\n and \n\n```\n\n```\n\n component from react-router. Details see doc Kulbear – Kulbear 05/24/2017 09: 08: 05 Commented May 24, 2017 at 9: 08 1 @Kulbear I had the same problem. Doing what Ogglas said in his answer worked. Alan P. – Alan P. 06/22/2017 23: 46: 13 Commented Jun 22, 2017 at 23: 46 2 To make it work you most likely need to put this route last or do this \n\n```\n\n```\n\n Aleksei Poliakov – Aleksei Poliakov 04/27/2019 19: 27: 43 Commented Apr 27, 2019 at 19: 27 It's easy to oversee it, so I repeat: The important part of DarkWalker's Redirect rule is the \n\n```\nexact\n```\n\n flag. The acceptet answer is missing that, so it matches [almost] any route. dube – dube 05/15/2019 11: 32: 22 Commented May 15, 2019 at 11: 32 | Show 2 more comments 101 Update for version 6. 4. 5 to 6. 8. 1 <: Use \n\n```\nreplace={true}\n```\n\n for \n\n```\nNavigate\n```\n\n component. \n\n```\n\n }>\n } />\n }\n />\n \n\n```\n\n https: //reactrouter. com/en/6. 4. 5/components/navigate https: //reactrouter. com/en/6. 8. 1/components/navigate Thanks to @vicky for pointing this out in comments. Update: For v6 you can do it like this with \n\n```\nNavigate\n```\n\n. You can use a \"No Match\" Route to handle \"no match\" cases. \n\n```\n\n }>\n } />\n }\n />\n \n\n```\n\n https: //reactrouter. com/docs/en/v6/getting-started/tutorial#adding-a-no-match-route https: //stackoverflow. com/a/69872699/3850405 Original: The problem with using \n\n```\n\n```\n\n is if you have a different URL, say \n\n```\n/indexDashboard\n```\n\n and the user hits refresh or gets a URL sent to them, the user will be redirected to \n\n```\n/searchDashboard\n```\n\n anyway. If you wan't users to be able to refresh the site or send URLs use this: \n\n```\n (\n \n)}/>\n```\n\n Use this if \n\n```\nsearchDashboard\n```\n\n is behind login: \n\n```\n (\n loggedIn ? (\n \n ) : (\n \n )\n)}/>\n```\n\n Share Improve this answer Follow edited Feb 18, 2023 at 14: 52 answered May 13, 2017 at 21: 09 Ogglas 71. 2k 42 42 gold badges 383 383 silver badges 478 478 bronze badges 3 It should be use replace in navigate otherwise there should be back event not work. }/ > vicky – vicky 02/18/2023 10: 04: 12 Commented Feb 18, 2023 at 10: 04 @vicky Updated the answer with \n\n```\nreplace={true}\n```\n\n Ogglas – Ogglas 02/18/2023 14: 53: 21 Commented Feb 18, 2023 at 14: 53 Just FYI your update for \n\n```\nreact-router@6\n```\n\n is incorrect, this code won't work. \n\n```\nNavigate\n```\n\n doesn't render an \n\n```\nOutlet\n```\n\n so none of the nested routes are reachable. Drew Reese – Drew Reese 09/30/2023 05: 32: 00 Commented Sep 30, 2023 at 5: 32 Add a comment | 38 I was incorrectly trying to create a default path with: \n\n```\n\n\n```\n\n But this creates two different paths that render the same component. Not only is this pointless, but it can cause glitches in your UI, i. e., when you are styling \n\n```\n\n```\n\n elements based on \n\n```\nthis.history.isActive()\n```\n\n. The right way to create a default route (that is not the index route) is to use \n\n```\n\n```\n\n: \n\n```\n\n\n```\n\n This is based on react-router 1. 0. 0. See https: //github. com/rackt/react-router/blob/master/modules/IndexRedirect. js. Share Improve this answer Follow edited Dec 8, 2015 at 0: 54 answered Dec 4, 2015 at 3: 19 Seth 6, 912 6 6 gold badges 54 54 silver badges 59 59 bronze badges 4 What's the point of having a \n\n```\nRoute\n```\n\n to something that is already handled by your \n\n```\nIndexRoute\n```\n\n? Matthew Herbst – Matthew Herbst 12/04/2015 03: 52: 13 Commented Dec 4, 2015 at 3: 52 1 There is no point, and I edited my answer to make it clear I was not advocating that. Seth – Seth 12/04/2015 03: 58: 19 Commented Dec 4, 2015 at 3: 58 This is what I've been doing as well, but I'd love a solution that serves up a component (my homepage) at \n\n```\n/\n```\n\n instead of having to redirect to e. g. \n\n```\n/home\n```\n\n. ericsoco – ericsoco 08/08/2016 23: 39: 11 Commented Aug 8, 2016 at 23: 39 Looks like I'm looking for \n\n```\n\n```\n\n after all. Sorry for the noise. stackoverflow. com/questions/32706913/… github. com/reactjs/react-router/blob/master/docs/guides/… ericsoco – ericsoco 08/08/2016 23: 42: 29 Commented Aug 8, 2016 at 23: 42 Add a comment | 15 Since V6 was released recently, the accepted answer won't work since Redirect no more exists in V6. Consider using \n\n```\nNavigate\n```\n\n. \n\n```\n} />\n```\n\n Ref: - V6 docs Share Improve this answer Follow edited Jan 7 at 8: 55 Penny Liu 17. 9k 5 5 gold badges 88 88 silver badges 109 109 bronze badges answered Dec 13, 2021 at 15: 24 Bijan Kundu Bijan Kundu 494 8 8 silver badges 15 15 bronze badges Add a comment | 13 2020: Instead of using Redirect, simply add multiple routes in the \n\n```\npath\n```\n\n. Example: \n\n```\n\n```\n\n UPDATE 2023 This doesn't work in v6, so use this instead \n\n```\n\n\n```\n\n Share Improve this answer Follow edited Sep 2, 2023 at 21: 17 answered Jun 18, 2020 at 16: 48 Thanveer Shah Thanveer Shah 3, 334 2 2 gold badges 20 20 silver badges 36 36 bronze badges 1 1 Hey are you sure there are square brackets there? Because I was getting the error: \n\n```\n\"Uncaught TypeError: meta.relativePath.startsWith is not a function\"\n```\n\n so when I removed the square brackets, it works fine, like this: \n\n```\n\n```\n\n Uzair_Abdullah – Uzair_Abdullah 01/09/2022 10: 30: 47 Commented Jan 9, 2022 at 10: 30 Add a comment | 12 Jonathan's answer didn't seem to work for me. I'm using React v0. 14. 0 and React Router v1. 0. 0-rc3. This did: \n\n```\n\n```\n\n. So in Matthew's Case, I believe he'd want: \n\n```\n\n```\n\n. Source: https: //github. com/rackt/react-router/blob/master/docs/guides/advanced/ComponentLifecycle. md Share Improve this answer Follow answered Oct 14, 2015 at 7: 16 dwilt 625 9 9 silver badges 13 13 bronze badges 2 Thanks for the share. I was using React v0. 13 and the version of React-Router for that, so a pre-1. 0/rc version. Hope this helps others! Matthew Herbst – Matthew Herbst 10/14/2015 14: 59: 34 Commented Oct 14, 2015 at 14: 59 I think this makes you lose the context. \n\n```\nSearchDashboard\n```\n\n will be the component you will see when you arrive at the homepage, but not the \n\n```\nDashboard\n```\n\n component that is wrapping it if you go directly to \n\n```\n/dashboard/searchDashboard\n```\n\n. React-router dynamically builds up a hierarchy of nested components based on the routes matched by the URL, so I think you really do need a redirect here. Stijn de Witt – Stijn de Witt 01/19/2016 12: 34: 59 Commented Jan 19, 2016 at 12: 34 Add a comment | 9 May 2022 Import \n\n```\nNavigate\n```\n\n \n\n```\nimport { Routes, Route, Navigate } from 'react-router-dom';\n```\n\n Add \n\n```\n} />\n```\n\n For example: \n\n```\nimport React from 'react';\nimport { Routes, Route, Navigate } from 'react-router-dom';\nimport Home from './pages/Home';\nimport Login from './pages/Login';\nconst Main = () => {\n return (\n \n } />\n }>\n }>\n \n );\n}\nexport default Main;\n```\n\n Done! Share Improve this answer Follow answered May 14, 2022 at 18: 27 hadeneh 131 1 1 silver badge 8 8 bronze badges Add a comment | 7 \n\n```\nimport { Route, Redirect } from \"react-router-dom\";\nclass App extends Component {\n render() {\n return (\n
\n \n \n \n//rest of code here\n```\n\n this will make it so that when you load up the server on local host it will re direct you to /something Share Improve this answer Follow answered Oct 3, 2018 at 21: 32 user2785628 Add a comment | 4 I ran into a similar issue; I wanted a default route handler if none of the route handler matched. My solutions is to use a wildcard as the path value. ie Also make sure it is the last entry in your routes definition. \n\n```\n\n \n \n \n \n\n```\n\n Share Improve this answer Follow answered Apr 30, 2017 at 2: 16 devil_io 191 2 2 silver badges 5 5 bronze badges Add a comment | 4 For those coming into 2017, this is the new solution with \n\n```\nIndexRedirect\n```\n\n: \n\n```\n\n \n \n \n\n```\n\n Share Improve this answer Follow answered Nov 2, 2017 at 0: 40 Kevin K Kevin K 525 1 1 gold badge 6 6 silver badges 20 20 bronze badges 0 Add a comment | 2 \n\n```\n\n \n \n \n \n \n \n \n```\n\n Share Improve this answer Follow answered Nov 18, 2016 at 19: 46 Saeid 19 3 3 bronze badges 2 What is equivalent of \n\n```\nDefaultRoute\n```\n\n in \n\n```\nreact-router\n```\n\n v4? Anthony Kong – Anthony Kong 03/22/2017 06: 08: 49 Commented Mar 22, 2017 at 6: 08 4 @AnthonyKong I think it is: \n\n```\n\n```\n\n. reacttraining. com/react-router/web/example/basic TYMG – TYMG 04/30/2017 16: 22: 49 Commented Apr 30, 2017 at 16: 22 Add a comment | 2 Use: \n\n```\n} />\n```\n\n In context: \n\n```\nimport { BrowserRouter, Routes, Route, Navigate } from \"react-router-dom\";\n\n \n }>\n } />\n } />\n \n } />\n \n\n```\n\n Share Improve this answer Follow answered Mar 21, 2022 at 21: 19 Bar Horing Bar Horing 6, 095 4 4 gold badges 36 36 silver badges 30 30 bronze badges Add a comment | 1 The preferred method is to use the react router IndexRoutes component You use it like this (taken from the react router docs linked above): \n\n```\n\n \n \n \n\n```\n\n Share Improve this answer Follow answered Mar 2, 2017 at 18: 00 Marc Costello Marc Costello 439 1 1 gold badge 3 3 silver badges 12 12 bronze badges 1 The linked page is giving 404 now Uzair_Abdullah – Uzair_Abdullah 01/09/2022 10: 20: 02 Commented Jan 9, 2022 at 10: 20 Add a comment | 1 Here is how I do it- \n\n```\n\n
\n \n \n
\n //Imp\n \n \n \n \n \n //Imp\n
\n
\n\n```\n\n Share Improve this answer Follow answered Jul 5, 2021 at 8: 51 prakhar tomar prakhar tomar 1, 145 1 1 gold badge 13 13 silver badges 13 13 bronze badges Add a comment | 1 Firstly you need to install: \n\n```\nnpm install react-router-dom;\n```\n\n Then you need to use your App. js (in your case it can be different) and do the modification below. In this case I selected the Redirect to get proper rendering process. \n\n```\nimport { BrowserRouter as Router, Route, Switch, Redirect } from \"react-router-dom\";\n\n }>\n \n \n \n \n \n \n \n \n```\n\n If you successfully do the modification above, you can see the redirect URL is on your browser path and rendering process also working properly according to their component. Some time ago, we had an opportunity to use the component named \"DefaultRoute\" in the react routing. Now, it's a deprecated method, and it’s not so popular to use it. You can create the custom route named default or whatever, but still, it’s not how we do it in modern React. js development. It’s just because using the \"DefaultRoute\" route, we can cause some rendering problems, and it's the thing that we definitely would like to avoid. Share Improve this answer Follow edited Jul 14, 2023 at 12: 22 Peter Mortensen 31. 6k 22 22 gold badges 110 110 silver badges 134 134 bronze badges answered Feb 28, 2021 at 20: 32 nipundimantha 41 4 4 bronze badges Add a comment | 1 Redirect to \n\n```\n/Home\n```\n\n when user goes to \n\n```\n/\n```\n\n (default Route): \n\n```\n} />\n```\n\n Use the \n\n```\nNavigate\n```\n\n element to redirect the user to \n\n```\n/Home\n```\n\n every time they go to the \n\n```\n/\n```\n\n route. Share Improve this answer Follow edited Jan 7 at 8: 53 Penny Liu 17. 9k 5 5 gold badges 88 88 silver badges 109 109 bronze badges answered Jul 13, 2023 at 6: 32 Avnish Jayaswal Avnish Jayaswal 469 6 6 silver badges 6 6 bronze badges Add a comment | 0 You use it like this to redirect on a particular URL and render component after redirecting from old-router to new-router. \n\n```\n\n \n \n\n```\n\n Share Improve this answer Follow answered May 7, 2020 at 9: 17 surbhi241 81 1 1 silver badge 2 2 bronze badges Add a comment | 0 Place the following code after all the exact routes. If none of them matches the current route, it'll render the default route. \n\n```\n} />\n```\n\n Share Improve this answer Follow edited Jul 14, 2023 at 12: 23 Peter Mortensen 31. 6k 22 22 gold badges 110 110 silver badges 134 134 bronze badges answered Mar 9, 2023 at 9: 51 Rakesh Gandla Rakesh Gandla 31 3 3 bronze badges Add a comment | 0 To create a default child route, here is what worked for me: \n\n```\nimport * as React from \"react\";\n import * as ReactDOM from \"react-dom\";\n import {\n createBrowserRouter,\n RouterProvider,\n} from \"react-router-dom\";\nconst router = createBrowserRouter([\n {\n path: \"/\",\n element: ,\n children: [\n {\n path: \"team\",\n element: ,\n },\n {\n path: \"aboutus\",\n element: ,\n },\n {\n path: \"\",\n element: ,\n },\n ],\n },\n]);\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n \n);\n```\n\n This will render IndexPageContent, at / route. ref: https: //reactrouter. com/en/main/routers/create-browser-router Share Improve this answer Follow answered May 5, 2024 at 15: 50 Murat Aka Murat Aka 1 1 1 silver badge 2 2 bronze badges Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript routes reactjs http-redirect react-router See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 231 How can I redirect in React Router v6? 113 React-Router: What is the purpose of IndexRoute? 3 Highlight default link in react router v4 2 How to make default route in ReactJS for child route concept 0 React-Router-Dom: Make Home The Landing Page 2 Active styling is correctly applied to a nested Route but not on the parent default path=”/” in React Router 0 How to make when opening the website to load the page /Home not / in ReactJS Related 3 React Router redirect using alternate route configuration 0 react-router: How to set default child route and modify URL accordingly 19 Default Route With React Router 4 2 How to change react-router routes? 0 React router, how to redirect a route to its sub route? 2 How to make default route in ReactJS for child route concept 1 React. js Redirect routing automatically 0 react. js set default route 0 React Redirect/Router 0 Redirect Route in React Hot Network Questions expr \"/foo\": \"/\" gives a syntax error Does Jesus' statement in Luke 21: 19 indicate that Stephen acted without the wisdom he should have received? Why did Hashem try killing Moses on his way to Egypt? Does the Apollo Command Module retain its docking probe for the return to Earth? Does the water content inside food regulate the cooking process? What are the biblical arguments against the idea of a post-mortem opportunity for salvation? How to sync Thunderbird emails, over two computers? How to show that the complement of an Archimedean spiral is open and connected? Can a SATA hard drive be hot swapped? PF2e: Raising a shield out of combat Have there been any 20th century onwards notable rabbanim from the Indian Jewish community? How to merge two tables with a different amount of columns in one table? Naming of parent keys and their modes Do the Apollo probe/drogues also serve as an airtight seal when not docked, or is there a separate seal? Looking for a short story collection, history of the universe starting with the big bang How can R and its associate software be distributed (incompatible LGPL 2. 1 and Apache 2) Do C++20 attributes [[likely]] and [[unlikely]] have anything to do with \"Speculative Execution\"? How can I attach the bottom of a window A. C. unit to the bottom of a window? Co-Lead Role Undermined, Manager Dismissive Program Generator: Print a Paragraph In UTF-8, why do two-byte codes range from U+0080 to U+07FF instead of U+0080 to U+087F In Luke 21: 16, is ‘they will put some of you to death’ meant literally or symbolically? How can EV9D9 torture droids? Birth control and the ambassador of the 22nd century more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 9.0,
- "coherence_score": 7.0,
- "word_count": 3555,
- "timestamp": "2025-09-03 07:33:16"
- }
- },
- {
- "id": "f27a5ea1ffce",
- "url": "https://github.com/microsoft/TypeScript/issues",
- "title": "GitHub · Where software is built",
- "content": "microsoft / TypeScript Public Notifications You must be signed in to change notification settings Fork 13k Star 106k TypeScript 5. 9 Iteration Plan # 61648 · DanielRosenwasser opened on May 2, 2025 32 TypeScript 5. 8 Iteration Plan # 61023 · DanielRosenwasser opened on Jan 22, 2025 34 Issues Search Issues is: issue state: open is: issue state: open Search Labels Milestones New issue Search results Open Closed Context sensitive inference fails with class instance Design Limitation Constraints of the existing architecture prevent this from being fixed Constraints of the existing architecture prevent this from being fixed Status: Open. # 62380 In microsoft/TypeScript; · Mike-Dax opened on Sep 2, 2025 Move to file refactor: Debug Failure. False expression: Changes overlap Bug A bug in TypeScript A bug in TypeScript Status: Open. # 62378 In microsoft/TypeScript; · Andarist opened on Sep 2, 2025 Method overloads fail to resolve correctly when using mapped types with conditional generics and optional parameters Needs More Info The issue still hasn't been fully clarified The issue still hasn't been fully clarified Status: Open. # 62377 In microsoft/TypeScript; · Ersaoktaviannn opened on Sep 2, 2025 Improve type inference in array filtering. Duplicate An existing issue was already created An existing issue was already created Status: Open. # 62376 In microsoft/TypeScript; · pjdotson opened on Sep 1, 2025 More human readable Memory used output when running tsc Declined The issue was declined as something which matches the TypeScript vision The issue was declined as something which matches the TypeScript vision Suggestion An idea for TypeScript An idea for TypeScript Status: Open. # 62374 In microsoft/TypeScript; · hamirmahal opened on Sep 1, 2025 [CLI] \"@\" character removed when it's first path character with --build Bug A bug in TypeScript A bug in TypeScript Help Wanted You can do this You can do this Status: Open. # 62373 In microsoft/TypeScript; · GongT opened on Sep 1, 2025 · Backlog No documentation for asserts keyword (assertion functions) Duplicate An existing issue was already created An existing issue was already created Status: Open. # 62372 In microsoft/TypeScript; · SystemParadox opened on Sep 1, 2025 @typescript-eslint/unbound-method error when using JSDoc @this {void} or alternatives Duplicate An existing issue was already created An existing issue was already created Status: Open. # 62371 In microsoft/TypeScript; · OhiraKyou opened on Sep 1, 2025 Key in mapped type not traversed when there's a something-with-generics extends clause in it Design Limitation Constraints of the existing architecture prevent this from being fixed Constraints of the existing architecture prevent this from being fixed Status: Open. # 62370 In microsoft/TypeScript; · Holzchopf opened on Sep 1, 2025 [ServerErrors][TypeScript] 6. 0. 0-dev. 20250831 vs 5. 9. 2 Status: Open. # 62369 In microsoft/TypeScript; · typescript-bot opened on Aug 31, 2025 \"basic\"/\"relative\" moduleResolution Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript An idea for TypeScript Status: Open. # 62368 In microsoft/TypeScript; · alshdavid opened on Aug 31, 2025 [ServerErrors][JavaScript] 6. 0. 0-dev. 20250831 vs 5. 9. 2 Status: Open. # 62367 In microsoft/TypeScript; · typescript-bot opened on Aug 31, 2025",
- "metadata": {
- "source_type": "github",
- "quality_score": 8.9,
- "coherence_score": 6.0,
- "word_count": 548,
- "timestamp": "2025-09-03 07:32:54"
- }
- },
- {
- "id": "e7a450709c26",
- "url": "https://stackoverflow.com/questions/51158080/typescript-cannot-find-name-errors-in-react-components",
- "title": "reactjs - Typescript - \"Cannot find name\" errors in React components - Stack Overflow",
- "content": "Typescript - \"Cannot find name\" errors in React components Ask Question Asked 7 years, 2 months ago Modified 11 months ago Viewed 182k times 157 I am migrating my existing React code over to TypeScript and I am hitting a lot of issues, one of them being a lot of \"Cannot find name\" errors when I make my \n\n```\n.js\n```\n\n files \n\n```\n.ts\n```\n\n files. Here is the code in question: \n\n```\nimport React from 'react';\nconst Footer = ({ children, inModal }) => (\n \n);\nexport default Footer;\n```\n\n The five lines from \n\n```\n\n```\n\n are underlined in red and give me various errors, depending where I hover my mouse, such as: Cannot find name 'footer'. ' > ' expected Cannot find name 'div' Unterminated regular expression literal Operator '<' cannot be applied to types 'boolean' and 'RegExp' Here is my \n\n```\ntsconfig.json\n```\n\n file: \n\n```\n{\n \"compilerOptions\": {\n \"outDir\": \"./dist/\", // path to output directory\n \"sourceMap\": true, // allow sourcemap support\n \"strictNullChecks\": true, // enable strict null checks as a best practice\n \"module\": \"es6\", // specify module code generation\n \"jsx\": \"react\", // use typescript to transpile jsx to js\n \"target\": \"es5\", // specify ECMAScript target version\n \"allowJs\": true, // allow a partial TypeScript and JavaScript codebase\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"lib\": [\n \"es6\",\n \"dom\"\n ],\n \"types\": [\n \"node\"\n ]\n },\n \"include\": [\n \"./src/\"\n ]\n}\n```\n\n I am incredibly confused and would greatly appreciate some help! reactjs typescript Share Improve this question Follow asked Jul 3, 2018 at 15: 20 noblerare 12k 26 26 gold badges 94 94 silver badges 170 170 bronze badges 5 4 Have you added the typings for React/React DOM? Also, maybe it should be named. tsx. Andrew Li – Andrew Li 07/03/2018 15: 22: 11 Commented Jul 3, 2018 at 15: 22 25 Is this code in a \n\n```\n. tsx\n```\n\n OR \n\n```\n. ts\n```\n\n file? To use \n\n```\njsx\n```\n\n the extension must be \n\n```\ntsx\n```\n\n Titian Cernicova-Dragomir – Titian Cernicova-Dragomir 07/03/2018 15: 22: 43 Commented Jul 3, 2018 at 15: 22 1 Although it seems like the error gets solved for everyone by renaming \n\n```\nts\n```\n\n - > \n\n```\ntsx\n```\n\n but not mine, because my file is already \n\n```\n.tsx\n```\n\n and it had happened multiple times but gets solved by itself. Circuit Planet – Circuit Planet 09/28/2022 23: 55: 19 Commented Sep 28, 2022 at 23: 55 @CircuitPlanet I am facing this issue, getting error in tsx files. Know how to fix it? Bilal Mohammad – Bilal Mohammad 05/14/2023 13: 58: 48 Commented May 14, 2023 at 13: 58 @TitianCernicova-Dragomir your hint helped me, i was confused by this error then I discovered that I was editing in a \n\n```\n.ts\n```\n\n file not \n\n```\n.tsx\n```\n\n Tarik Waleed – Tarik Waleed 04/28/2024 15: 49: 30 Commented Apr 28, 2024 at 15: 49 Add a comment | 11 Answers 11 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 389 Typescript isn't expecting to see JSX in your Typescript file. The easiest way to resolve this is to rename your file from \n\n```\n.ts\n```\n\n to \n\n```\n.tsx\n```\n\n. JSX in Typescript Documentation Share Improve this answer Follow edited May 10, 2019 at 15: 45 answered Jul 3, 2018 at 15: 23 coreyward 80. 4k 21 21 gold badges 147 147 silver badges 176 176 bronze badges 13 2 Thanks for the answer. This worked for me. All my previous JSX files were using \n\n```\n.js\n```\n\n extension so I just figured changing it to \n\n```\n.ts\n```\n\n would be okay. Even though this works for me, I'm curious as to if you know of another way to resolve this especially because changing everything to \n\n```\n.tsx\n```\n\n would require renaming all of my module imports. noblerare – noblerare 07/03/2018 15: 29: 36 Commented Jul 3, 2018 at 15: 29 1 This can also occur when a file is mistakenly named \n\n```\n.ts\n```\n\n instead of \n\n```\n.tsx\n```\n\n Lunster – Lunster 05/08/2019 12: 03: 40 Commented May 8, 2019 at 12: 03 @Lunster That's exactly what the question is about. coreyward – coreyward 05/08/2019 14: 53: 41 Commented May 8, 2019 at 14: 53 @coreyward No, not exactly, but analogous yes. The original question was about jsx and tsx, whereas I found this page on Google with the same error, but the cause was ts instead of tsx files. Your answer would not be a solution to my problem unless reformulated to be more general. Lunster – Lunster 05/09/2019 08: 54: 30 Commented May 9, 2019 at 8: 54 @Lunster Original question: ‚ÄúI'm hitting a lot of issues‚Ķwhen I make my. js files. ts files. ‚Äù. coreyward – coreyward 05/09/2019 16: 34: 49 Commented May 9, 2019 at 16: 34 | Show 8 more comments 14 If you have \". tsx\" file and still getting error then, you should add/modify value for \"jsx\" from \"preserve\" -- > \"react-jsx\" as below in tsconfig. json. Now, you must stop and restart the server again. \n\n```\n{\n \"compilerOptions\": {\n \"jsx\": \"react-jsx\", // üëàchange here\n ...\n ...\n}\n```\n\n Share Improve this answer Follow answered Feb 16, 2023 at 17: 13 bharatadk 639 5 5 silver badges 12 12 bronze badges 2 1 I did the same, but still it's not working for me. Vijay Dhanvai – Vijay Dhanvai 01/06/2024 05: 57: 33 Commented Jan 6, 2024 at 5: 57 1 Hah. VS Code said otherwise: We detected TypeScript in your project and reconfigured your tsconfig. json file for you. Strict-mode is set to false by default. The following mandatory changes were made to your tsconfig. json: - jsx was set to preserve (next. js implements its own optimized jsx transform) Robbie Smith – Robbie Smith 04/09/2024 18: 07: 58 Commented Apr 9, 2024 at 18: 07 Add a comment | 9 This issue can also arise if, having created. tsx files, you don't include them in the tsconfig file: \n\n```\n\"include\": [\n \"wwwroot/js/**/*.ts\",\n \"wwwroot/js/**/*.tsx\" // <-- this needed to be added in my case\n],\n```\n\n Share Improve this answer Follow answered Feb 10, 2023 at 8: 44 Mike Brind Mike Brind 30. 3k 6 6 gold badges 65 65 silver badges 95 95 bronze badges Add a comment | 3 I already had. tsx files in src in a create-react-app project and I could see the project was running fine. Simply turning VSCode off and on again solved this for me. Share Improve this answer Follow answered Apr 27, 2023 at 15: 19 Matthias 4, 190 2 2 gold badges 32 32 silver badges 46 46 bronze badges 0 Add a comment | 2 Another subtle way this can happen is if you \n\n```\ntsconfig.json\n```\n\n doesn't \"include\" the file that's giving the editor warning. You still have to get the other configs correct, and they vary depending on bundler and TypeScript version. See https: //preactjs. com/guide/v10/typescript#typescript-configuration for advice, most of which is covered in posts above this. But before you mess with those settings make sure the \n\n```\ntsconfig.json\n```\n\n at project root is telling VSCode that your file is to be treated as TypeScript. This example assumes your source files are under \n\n```\n./src\n```\n\n \n\n```\n// tsconfig.json excerpt\n{\n // COMMON PROBLEM 1: this include ignores .tsx files\n // \"include\": [\"./src/**/*.ts\"],\n // COMMON PROBLEM 2: this include ignores subdirectories\n // \"include\": [\"./src/*.ts?\"],\n // THIS IS PROBABLY CLOSE TO WHAT YOU WANT\n \"include\": [\"./src/**/*.ts?\"],\n....\n}\n```\n\n Share Improve this answer Follow answered Sep 21, 2023 at 18: 51 bradobro 161 1 1 silver badge 4 4 bronze badges Add a comment | 2 In my case I had a. tsx file but my error didn't gone. when I removed \n\n```\nimport React from \"react\";\n```\n\n from top of my next. js, the error was gone. Share Improve this answer Follow answered Dec 26, 2023 at 12: 24 mohammad barzegar mohammad barzegar 387 6 6 silver badges 12 12 bronze badges Add a comment | 1 I had this error in a file with no extension. It was simply \n\n```\nfilename\n```\n\n without extensions so VSCode assumed it to be TS. When I renamed my file to \n\n```\nfilename.js\n```\n\n the error went away. Though, If you want the file to be in typescript and don't want the error, the accepted answer ( \n\n```\nfilename.tsx\n```\n\n ) is the correct approach. Share Improve this answer Follow answered Oct 8, 2021 at 5: 35 Abdul Hameed Abdul Hameed 992 12 12 silver badges 28 28 bronze badges Add a comment | 1 Just in case others come across this. I use StencilJS, which uses react-like tsx files, without react. My issue was that I loaded the SRC directory in vscode. The correction is loading the parent of the SRC directory, which has the appropriate config. ts, tsconfig. json, etc. This allowed it to recognize tsx files correctly. Share Improve this answer Follow answered Jan 15, 2023 at 21: 40 Jim Jim 814 1 1 gold badge 7 7 silver badges 18 18 bronze badges Add a comment | 1 If after changing the file name to tsx you are still facing the issue there might be a chance that your file association for typescript files in vscode is to Typescript, you have to change it to Typescript Jsx if you are using. tsx files. Share Improve this answer Follow answered Jul 2, 2024 at 10: 33 Muhammad Talha Qaisar Muhammad Talha Qaisar 11 1 1 bronze badge Add a comment | 0 if this happens to you and are using vite as your bundler. Make sure both tsconfig. json and tsconfig. node. json file have \n\n```\n\"jsx\": \"react-jsx\",\n```\n\n in the compilerOptions. Share Improve this answer Follow answered May 10, 2023 at 14: 30 Peter Mugendi Peter Mugendi 1, 005 1 1 gold badge 13 13 silver badges 20 20 bronze badges Add a comment | 0 Actually for me the issue was that I was using a different typescript version than the other team member and some of the features in the code were not supported by mine (obsolete) version. Increasing typescript version fixed the issue. Share Improve this answer Follow answered Jun 10, 2024 at 12: 36 Mateusz Pietras Mateusz Pietras 119 1 1 silver badge 3 3 bronze badges Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking ‚ÄúPost Your Answer‚Äù, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions reactjs typescript See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn‚Äôt all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 48 How to setup TypeScript + Babel + Webpack? 0 React Native BottomTabNavigator navigation not working Related 3 React TS2304 error: Cannot find name 'Component' 0 Typescript React Error 0 Need help solving a React Typescript error 1 React + Typescript error 34 React Typescript: Line 0: Parsing error: Cannot read property 'name' of undefined 1 Getting typescript errors with any 0 Typescript - Property 'name' does not exist on type '{}' 3 Property 'name' does not exist on type 'object' TypeScript 1 Typescript: type is object where property names are unknown 0 Property 'name' does not exist on type 'never'. ts(2339) Hot Network Questions Conjecture possibly related to Hardy-Littlewood II xargs -I {} not replacing with input string, says \"/usr/bin/xargs: {}: No such file or directory\" Appendix by a subset of the authors of the main paper How does the capacitive sensing works on the PC / PC/XT keyboard type 2? Uniform convergence of metrics imply that induced topologies are equal and possible error in Burago, Ivanov's \"A Course in Metric Geometry\" What did Jesus eat in relationship to his Jewish culture and tradition? Using a digital potentiometer compared to 'real resistors' for variable gain audio amplifier 90-00s TV show. Colony established on a habitable planet. Colony is surrounded by a large wall. Expedition outside the wall encounter exiled group Find the correct door part 2 Co-Lead Role Undermined, Manager Dismissive Keep two entire Linux desktop systems in sync How to write \"the positive sign is replaced by negative sign and negative sign by positive sign\"? When would a court impose a harsher sentence than the prosecutor requests? Do these ground connections look ok? In what American magazine was Tolkien's \"Smith of Wootton Major\" first published? Extra space after \\left…\\right workaround with \\vphantom in LaTeX c++ format_to verbosity In search of 86-DOS ttsr. h and corresponding library What is a voice leading (Guitar notation) Does Innate Sorcery grant Advantage to True Strike? How to sync Thunderbird emails, over two computers? In \"Little Women\" (1949), what is the German song sung and played on the piano by Professor Bhaer? What was the first game where your guide/quest giver turned out to be a key antagonist/villain? Knowledge is free, but time costs money? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 8.9,
- "coherence_score": 7.0,
- "word_count": 2259,
- "timestamp": "2025-09-03 07:33:15"
- }
- },
- {
- "id": "a971fc11a938",
- "url": "https://stackoverflow.com/questions/36002226/parsing-error-the-keyword-import-is-reserved-sublimelinter-contrib-eslint",
- "title": "javascript - Parsing Error The Keyword import is Reserved (SublimeLinter-contrib-eslint) - Stack Overflow",
- "content": "Parsing Error The Keyword import is Reserved (SublimeLinter-contrib-eslint) Ask Question Asked 9 years, 5 months ago Modified 1 year, 9 months ago Viewed 260k times 146 I have a problem with eslint, it gives me [Parsing Error The keyword import is reserve] this is only occur in sublime, in atom editor work well. I have eslint. eslintrc. js \n\n```\nmodule.exports = {\n \"extends\": \"airbnb\",\n \"plugins\": [\n \"react\"\n ]\n};\n```\n\n package. json \n\n```\n{\n \"name\": \"paint\",\n \"version\": \"0.0.0\",\n \"description\": \"paint on the browser\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"keywords\": [\n \"paint\",\n \"javascript\"\n ],\n \"author\": \"\",\n \"license\": \"ISC\",\n \"devDependencies\": {\n \"browserify\": \"^11.2.0\",\n \"eslint\": \"^2.2.0\",\n \"eslint-config-airbnb\": \"^2.1.1\",\n \"eslint-plugin-react\": \"^3.11.2\",\n \"gulp-babel\": \"^5.2.1\",\n \"gulp-clean\": \"^0.3.1\",\n \"gulp-stylus\": \"^2.2.0\",\n \"vinyl-source-stream\": \"^1.1.0\"\n }\n}\n```\n\n javascript parsing sublimetext eslint Share Improve this question Follow edited Jan 18, 2018 at 11: 25 paulhhowells 321 3 3 silver badges 11 11 bronze badges asked Mar 15, 2016 at 3: 33 pedro luis pedro luis 1, 745 2 2 gold badges 11 11 silver badges 8 8 bronze badges Add a comment | 15 Answers 15 Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 259 Add this to the root of your \n\n```\n.eslintrc.json\n```\n\n (formerly \n\n```\n.eslintrc\n```\n\n ) \n\n```\n\"parser\": \"babel-eslint\"\n```\n\n and make sure to run: \n\n```\nnpm install babel-eslint --save-dev\n```\n\n Share Improve this answer Follow edited Feb 22, 2022 at 14: 25 Henke 5, 879 6 6 gold badges 41 41 silver badges 52 52 bronze badges answered Dec 16, 2016 at 18: 18 Iman Mohamadi Iman Mohamadi 6, 849 3 3 gold badges 37 37 silver badges 33 33 bronze badges 9 19 This worked for me too, thanks. If it helps anyone, my entire. eslint file is \n\n```\n{\"parser\": \"babel-eslint\"}\n```\n\n Mark Madej – Mark Madej 07/26/2017 04: 12: 04 Commented Jul 26, 2017 at 4: 12 19 No need to change the parser. Doing \n\n```\n\"parserOptions\": { \"sourceType\": \"module\" }\n```\n\n is enough nathancahill – nathancahill 10/31/2018 01: 23: 36 Commented Oct 31, 2018 at 1: 23 9 As of July-2021, { \"parser\": \"@babel/eslint-parser\" } JustinC – JustinC 07/21/2021 16: 50: 22 Commented Jul 21, 2021 at 16: 50 6 But why does adding \n\n```\nbabel-eslint\n```\n\n work? Just setting parseOptions/sourceType to \"module\" is not enough according to what I experience. bytrangle – bytrangle 07/25/2022 10: 49: 47 Commented Jul 25, 2022 at 10: 49 4 sourceType 'module' is not supported when ecmaVersion < 2015. Adding \n\n```\n\"ecmaVersion\": 6\n```\n\n may be also necessary. josemigallas – josemigallas 06/13/2023 09: 09: 28 Commented Jun 13, 2023 at 9: 09 | Show 4 more comments 113 The eslint option that solves the \"The keyword import is reserved\" error is \n\n```\nparserOptions.sourceType\n```\n\n. Setting it to \n\n```\n\"module\"\n```\n\n allows the \n\n```\nimport\n```\n\n keyword to be used. . eslintrc \n\n```\n{\n \"parserOptions\": {\n \"sourceType\": \"module\"\n }\n}\n```\n\n Docs: https: //eslint. org/docs/user-guide/configuring#specifying-parser-options Share Improve this answer Follow edited Oct 31, 2018 at 1: 37 nathancahill 10. 9k 11 11 gold badges 56 56 silver badges 93 93 bronze badges answered Jul 21, 2017 at 6: 33 user8202629 2 2 Additionally, although I do not use babel, \n\n```\nnpm install babel-eslint --save-dev\n```\n\n and \n\n```\nparser: 'babel-eslint'\n```\n\n were needed to get rid of the 'import is reserved' error. It is not a good solution but a workaround recommended by eslint for now. Akseli Palén – Akseli Palén 02/02/2021 22: 21: 31 Commented Feb 2, 2021 at 22: 21 10 Yes, but I also had to add \n\n```\n\"ecmaVersion\": \"latest\"\n```\n\n under \n\n```\nparserOptions\n```\n\n. Michael Cox – Michael Cox 12/15/2022 21: 44: 52 Commented Dec 15, 2022 at 21: 44 Add a comment | 19 The problem was i had installed eslint globally and locally, causing inconsistencies in SublimeLinter-contrib-eslint. I uninstalled eslint globally and SublimeLinter is working. Share Improve this answer Follow answered Mar 25, 2016 at 4: 59 pedro luis pedro luis 1, 745 2 2 gold badges 11 11 silver badges 8 8 bronze badges 2 Thanks for this. IMO this problem may more universal that just SublimeLinter. Matt Jensen – Matt Jensen 10/28/2016 20: 24: 10 Commented Oct 28, 2016 at 20: 24 Stems from module-type syntax. CommonJS module uses 'require'. Stephen W. Wright – Stephen W. Wright 06/17/2017 04: 13: 34 Commented Jun 17, 2017 at 4: 13 Add a comment | 16 Closing VS code and re-open it does the trick for me. . . Share Improve this answer Follow answered May 23, 2020 at 21: 36 JulienRioux 3, 122 2 2 gold badges 28 28 silver badges 40 40 bronze badges 1 1 The same solved the problem with WebStorm Tatyana Molchanova – Tatyana Molchanova 06/20/2022 08: 21: 43 Commented Jun 20, 2022 at 8: 21 Add a comment | 11 The currently highest voted answer works. However, it is no longer under maintenance and the newly suggested approach is to use the version from the mono repo instead. Installation \n\n```\n$ npm install eslint @babel/core @babel/eslint-parser --save-dev\n# or\n$ yarn add eslint @babel/core @babel/eslint-parser -D\n```\n\n. eslintrc. js \n\n```\nmodule.exports = {\n parser: \"@babel/eslint-parser\",\n};\n```\n\n Reference Share Improve this answer Follow edited Nov 15, 2023 at 15: 38 Henke 5, 879 6 6 gold badges 41 41 silver badges 52 52 bronze badges answered Aug 16, 2021 at 20: 58 Crisoforo Gaspar Crisoforo Gaspar 3, 840 2 2 gold badges 23 23 silver badges 27 27 bronze badges Add a comment | 9 Not sure about it but try to rename your file to. eslintrc and just use \n\n```\n{\n \"extends\": \"airbnb\",\n \"plugins\": [\"react\"]\n};\n```\n\n Also be sure you have the required packages installed. github. com/airbnb/javascript Share Improve this answer Follow answered Mar 20, 2016 at 9: 26 the the 119 3 3 bronze badges 5 1 I solved the error, the problem was i had eslint globally and locally. Thanks pedro luis – pedro luis 03/25/2016 04: 46: 07 Commented Mar 25, 2016 at 4: 46 2 Oddly the \n\n```\n.eslintrc.js\n```\n\n to \n\n```\n.eslintrc\n```\n\n fixed it for me, weird. Thanks! JREAM – JREAM 12/29/2018 17: 56: 01 Commented Dec 29, 2018 at 17: 56 jfyi - This din't work for VS Code, with or without global eslint installation. Manohar Reddy Poreddy – Manohar Reddy Poreddy 04/30/2020 05: 29: 50 Commented Apr 30, 2020 at 5: 29 I spent a while on this before realizing that I'd named my file \n\n```\neslintrc.js\n```\n\n and not \n\n```\n.eslintrc.js\n```\n\n (no leading dot). danvk – danvk 02/13/2022 16: 06: 31 Commented Feb 13, 2022 at 16: 06 Renaming \n\n```\n.eslintrc.js\n```\n\n to \n\n```\n.eslintrc.cjs\n```\n\n worked for me. John Y – John Y 10/03/2022 15: 55: 21 Commented Oct 3, 2022 at 15: 55 Add a comment | 3 i also got this error in a meteor project and i could solved it setting sourceType to \"module\" more details can be found in Eslint docs: http: //eslint. org/docs/user-guide/configuring#specifying-parser-options Share Improve this answer Follow answered Feb 24, 2017 at 9: 12 SPM SPM 31 3 3 bronze badges 1 jfyi - This din't work for VS Code, copy pasted in parserOptions > sourceType. Manohar Reddy Poreddy – Manohar Reddy Poreddy 04/30/2020 05: 33: 57 Commented Apr 30, 2020 at 5: 33 Add a comment | 3 This config worked for me. (I am using create-react-app but applicable to any eslint project) \n\n```\n.eslintrc (create file in root if it doesnt exist)\n```\n\n \n\n```\n{\n \"rules\": {\n \"jsx-a11y/anchor-is-valid\": [ \"error\", {\n \"components\": [ \"Link\" ],\n \"specialLink\": [ \"to\" ]\n }]\n },\n \"parserOptions\": {\n \"sourceType\": \"module\",\n \"ecmaVersion\": 2015\n }\n }\n```\n\n Share Improve this answer Follow answered Dec 23, 2019 at 5: 50 Nitin Jadhav Nitin Jadhav 7, 376 3 3 gold badges 52 52 silver badges 51 51 bronze badges Add a comment | 3 The same issue occurred when creating \n\n```\njs\n```\n\n files within a typescript react-native project while eslint is enabled. Changing the file type from \n\n```\njs\n```\n\n to \n\n```\nts\n```\n\n resolved the issue. Also, adding the. eslintrc. js file as mentioned in previous answers resolved the issue without changing the file type from \n\n```\njs\n```\n\n to \n\n```\nts\n```\n\n. \n\n```\nmodule.exports = {\n parser: \"@babel/eslint-parser\",\n };\n```\n\n Share Improve this answer Follow answered Aug 24, 2021 at 15: 27 Mohammad Fasha Mohammad Fasha 478 5 5 silver badges 10 10 bronze badges Add a comment | 3 The issue is seen with the new react app, and in Visual Studio Code, even at this time - August 2022 Create a file \n\n```\n.eslintrc.js\n```\n\n in the root folder Paste the below contents in \n\n```\n.eslintrc.js\n```\n\n Restart your editor, like VS Code. Now I can see real errors, instead of those fake import/export errors. \n\n```\n.eslintrc.js\n```\n\n file contents: \n\n```\nexport const parser = \"@babel/eslint-parser\";\n```\n\n The accepted answer works, however, the newly suggested approach is to use the version from ES6. Share Improve this answer Follow edited Aug 3, 2022 at 7: 49 skr 1, 841 1 1 gold badge 18 18 silver badges 49 49 bronze badges answered Jul 31, 2022 at 23: 21 Arvind Maurya Arvind Maurya 31 2 2 bronze badges Add a comment | 1 Adding ecmaVersion to. eslintrc. json fixed the issue \n\n```\n{\n \"ecmaVersion\": 2015,\n \"extends\": [\n \"eslint:recommended\",\n \"plugin:react/recommended\"\n ]\n}\n```\n\n Share Improve this answer Follow answered Oct 7, 2021 at 5: 01 Gvs Akhil Gvs Akhil 2, 884 2 2 gold badges 23 23 silver badges 40 40 bronze badges Add a comment | 1 I found this issue while creating the vue project (Used Editor: Visual Code) Install babel-eslint package npm install babel-eslint Create the \n\n```\n.eslintrc.js\n```\n\n file and add below code \n\n```\nmodule.exports = {\n root: true,\n parserOptions: {\n 'sourceType': 'module',\n parser: 'babel-eslint' \n }\n}\n```\n\n \n\n```\nnpm run serve\n```\n\n, that error will be resolved like magic. Share Improve this answer Follow edited Sep 21, 2022 at 20: 13 Sreekumar P 6, 058 12 12 gold badges 61 61 silver badges 84 84 bronze badges answered Mar 16, 2020 at 0: 47 Bhupinder 11 2 2 bronze badges 1 OR, try without 'sourceType' module. exports = { root: true, parserOptions: { parser: 'babel-eslint' } } Bhupinder – Bhupinder 03/16/2020 01: 08: 17 Commented Mar 16, 2020 at 1: 08 Add a comment | 1 ESlint the disabling rules in. eslintrc. json file. \n\n```\n{\n \"extends\": \"next\",\n \"rules\": {\n \"react/no-unescaped-entities\": \"off\",\n \"@next/next/no-page-custom-font\": \"off\"\n }\n}\n```\n\n Share Improve this answer Follow answered Jul 11, 2023 at 10: 27 Apurv 147 9 9 bronze badges Add a comment | 1 I have been facing this error on next. js 13 today and my eslint file looks like this: \n\n```\n{\n \"root\": true,\n \"settings\": {\n \"react\": {\n \"version\": \"detect\"\n },\n \"env\": {\n \"browser\": true,\n \"node\": true,\n \"es2020\": true,\n \"jest\": true\n },\n \"extends\": [\n \"eslint:recommended\",\n \"plugin:react/recommended\",\n \"plugin:react-hooks/recommended\",\n \"plugin:@typescript-eslint/recommended\",\n \"plugin:prettier/recommended\"\n ],\n \"parser\": \"@typescript-eslint/parser\",\n \"parserOptions\": {\n \"ecmaVersion\": \"latest\",\n \"sourceType\": \"module\",\n \"ecmaFeatures\": {\n \"jsx\": true\n }\n },\n \"plugins\": [\"react\", \"react-hooks\", \"@typescript-eslint\"],\n \"rules\": {}\n }\n}\n```\n\n So I removed this piece of code and it works fine: \n\n```\n\"settings\": {\n \"react\": {\n \"version\": \"detect\"\n }\n```\n\n Share Improve this answer Follow answered Sep 7, 2023 at 17: 24 joaovitorfelix 103 1 1 gold badge 3 3 silver badges 7 7 bronze badges Add a comment | 0 For me VSCode the eslint extension had a problem and after disabling it for current workspace it worked Share Improve this answer Follow answered Dec 1, 2023 at 12: 48 Daniel Barbakadze Daniel Barbakadze 211 2 2 silver badges 16 16 bronze badges Add a comment | Your Answer Draft saved Draft discarded Sign up or log in Sign up using Google Sign up using Email and Password Submit Post as a guest Name Email Required, but never shown Post Your Answer Discard By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Start asking to get answers Find the answer to your question by asking. Ask question Explore related questions javascript parsing sublimetext eslint See similar questions with these tags. The Overflow Blog Open-source is for the people, by the people Building AI for consumer applications isn’t all fun and games Featured on Meta Community Asks Sprint Announcement - September 2025 Policy: Generative AI (e. g., ChatGPT) is banned New comment UI experiment graduation Linked 18 \"Parsing error: The keyword 'import' is reserved\" 8 How to feature-detect whether a browser supports dynamic ES6 module loading? 6 Pulled from remote repo and getting: \"Parsing error: The keyword 'import' is reserved\" 0 trying to build rollup + babel + react starter, but get error during the building 0 Error when trying to deploy NextJS app on Vercel Related 1932 What is the 'new' keyword in JavaScript? 373 ESLint: \"error Parsing error: The keyword 'const' is reserved\" 3362 Why does my JavaScript code receive a \"No 'Access-Control-Allow-Origin' header is present on the requested resource\" error, while Postman does not? 1664 What is the purpose of the var keyword and when should I use it (or omit it)? 1499 How does the \"this\" keyword work, and when should it be used? 334 How do you fix ESLint Parsing error: Unexpected token error 291 Parsing error: Cannot read file '. . . /tsconfig. json'. eslint 1238 Error: Can't set headers after they are sent to the client 326 Object. hasOwnProperty() yields the ESLint 'no-prototype-builtins' error: how to fix? 204 ESLint - Error: Must use import to load ES Module Hot Network Questions What is this slot in the Cessna 152's interior sidewall? What was the first game where your guide/quest giver turned out to be a key antagonist/villain? What do I do if a DB Bahn train is late for an OBB connection? What is the measure of the new angle? Tiling a rectangle with heptominoes Find the correct door part 2 How can EV9D9 torture droids? Why is cinnamic acid nitrated at the ortho, para positions and not the meta position? What is a voice leading (Guitar notation) Is a condition termed a \"disease\" only when it has a known cause? Why did Hashem try killing Moses on his way to Egypt? If we have no free will, wherein lies the illusion? Can a SATA hard drive be hot swapped? Meaning of '#' suffix on SQL Server columns c++ format_to verbosity Why does Earth have the largest mean density of all the planets in the solar system? Why does MathML display differentiation operator weirdly when using ⅆ ? How does one get more oxyfern? Volume-preserving fluid flows are incompressible. What about surface-area preserving flows? How does the capacitive sensing works on the PC / PC/XT keyboard type 2? How to sync Thunderbird emails, over two computers? How to find \"minimal polynomial\" of a rational number? Do these ground connections look ok? How to prove that natural number less than is irrelevant? more hot questions Question feed lang-js",
- "metadata": {
- "source_type": "stackoverflow",
- "quality_score": 8.9,
- "coherence_score": 7.0,
- "word_count": 2515,
- "timestamp": "2025-09-03 07:33:17"
- }
- },
- {
- "id": "d1640fd35dd3",
- "url": "https://reactpatterns.com/",
- "title": "React Patterns",
- "content": "React Patterns on GitHub # Get the latest React patterns, tips, and tricks right to your inbox. Contents # Contents Translations Element Component Expressions Props defaultProps Destructuring props JSX spread attributes Merge destructured props with other values Conditional rendering Children types Array as children Function as children Render prop Children pass-through Proxy component Style component Event switch Layout component Container component Higher-order component State hoisting Controlled input Translations # These translations are not verified and links are not endorsements. Chinese Element # Elements are anything inside angle brackets. \n\n```\n\n\n```\n\n Components return Elements. Component # Define a Component by declaring a function that returns a React Element. \n\n```\nfunction Greeting() {\n return
Hi there!
;\n}\n```\n\n Expressions # Use curly braces to embed expressions in JSX. \n\n```\nfunction Greeting() {\n let name = \"chantastic\";\n return
Hi {name}!
;\n}\n```\n\n Props # Take \n\n```\nprops\n```\n\n as an argument to allow outside customizations of your Component. \n\n```\nfunction Greeting(props) {\n return
Hi {props.name}!
;\n}\n```\n\n defaultProps # Specify default values for \n\n```\nprops\n```\n\n with \n\n```\ndefaultProps\n```\n\n. \n\n```\nfunction Greeting(props) {\n return
Hi {props.name}!
;\n}\nGreeting.defaultProps = {\n name: \"Guest\",\n};\n```\n\n Destructuring props # Destructuring assignment is a JavaScript feature. It was added to the language in ES2015. So it might not look familiar. Think of it like the opposite of literal assignment. \n\n```\nlet person = { name: \"chantastic\" };\nlet { name } = person;\n```\n\n Works with Arrays too. \n\n```\nlet things = [\"one\", \"two\"];\nlet [first, second] = things;\n```\n\n Destructuring assignment is used a lot in function components. These component declarations below are equivalent. \n\n```\nfunction Greeting(props) {\n return
Hi {props.name}!
;\n}\nfunction Greeting({ name }) {\n return
Hi {name}!
;\n}\n```\n\n There's a syntax for collecting remaining \n\n```\nprops\n```\n\n into an object. It's called rest parameter syntax and looks like this. \n\n```\nfunction Greeting({ name, ...restProps }) {\n return
Hi {name}!
;\n}\n```\n\n Those three dots ( \n\n```\n...\n```\n\n ) take all the remaining properties and assign them to the object \n\n```\nrestProps\n```\n\n. So, what do you do with \n\n```\nrestProps\n```\n\n once you have it? Keep reading. . . JSX spread attributes # Spread Attributes is a feature of JSX. It's a syntax for providing an object's properties as JSX attributes. Following the example from Destructuring props, We can spread \n\n```\nrestProps\n```\n\n over our \n\n```\n
;\n}\n```\n\n This makes \n\n```\nGreeting\n```\n\n super flexible. We can pass DOM attributes to \n\n```\nGreeting\n```\n\n and trust that they'll be passed through to \n\n```\ndiv\n```\n\n. \n\n```\n\n```\n\n Avoid forwarding non-DOM \n\n```\nprops\n```\n\n to components. Destructuring assignment is popular because it gives you a way to separate component-specific props from DOM/platform-specific attributes. \n\n```\nfunction Greeting({ name, ...platformProps }) {\n return
Hi {name}!
;\n}\n```\n\n Merge destructured props with other values # Components are abstractions. Good abstractions allow for extension. Consider this component that uses a \n\n```\nclass\n```\n\n attribute for style a \n\n```\nbutton\n```\n\n. \n\n```\nfunction MyButton(props) {\n return ;\n}\n```\n\n This works great until we try to extend it with another class. \n\n```\nDelete...\n```\n\n In this case, \n\n```\ndelete-btn\n```\n\n replaces \n\n```\nbtn\n```\n\n. Order matters for JSX spread attributes. The \n\n```\nprops.className\n```\n\n being spread is overriding the \n\n```\nclassName\n```\n\n in our component. We can change the order but now the \n\n```\nclassName\n```\n\n will never be anything but \n\n```\nbtn\n```\n\n. \n\n```\nfunction MyButton(props) {\n return ;\n}\n```\n\n We need to use destructuring assignment to get the incoming \n\n```\nclassName\n```\n\n and merge with the base \n\n```\nclassName\n```\n\n. We can do this simply by adding all values to an array and joining them with a space. \n\n```\nfunction MyButton({ className, ...props }) {\n let classNames = [\"btn\", className].join(\" \");\n return ;\n}\n```\n\n To guard from \n\n```\nundefined\n```\n\n showing up as a className, you could update your logic to filter out \n\n```\nfalsy\n```\n\n values: \n\n```\nfunction MyButton({ className, ...props }) {\n let classNames = [\"btn\", className].filter(Boolean).join(\" \").trim();\n return ;\n}\n```\n\n Bear in mind though that if an empty object is passed it'll be included in the class as well, resulting in: \n\n```\nbtn [object Object]\n```\n\n. The better approach is to make use of available packages, like classnames or clsx, that could be used to join classnames, relieving you from having to deal with it manually. Conditional rendering # You can't use if/else statements inside a component declarations. So conditional (ternary) operator and short-circuit evaluation are your friends. \n\n```\nif\n```\n\n # \n\n```\n{\n condition && Rendered when `truthy`;\n}\n```\n\n \n\n```\nunless\n```\n\n # \n\n```\n{\n condition || Rendered when `falsy`;\n}\n```\n\n \n\n```\nif-else\n```\n\n # \n\n```\n{\n condition ? (\n Rendered when `truthy`\n ) : (\n Rendered when `falsy`\n );\n}\n```\n\n Children types # React can render \n\n```\nchildren\n```\n\n from most types. In most cases it's either an \n\n```\narray\n```\n\n or a \n\n```\nstring\n```\n\n. \n\n```\nString\n```\n\n # \n\n```\n
Hello World!
\n```\n\n \n\n```\nArray\n```\n\n # \n\n```\n
{[\"Hello \", World, \"!\"]}
\n```\n\n Array as children # Providing an array as \n\n```\nchildren\n```\n\n is a very common. It's how lists are drawn in React. We use \n\n```\nmap()\n```\n\n to create an array of React Elements for every value in the array. \n\n```\n
\n {[\"first\", \"second\"].map((item) => (\n
{item}
\n ))}\n
\n```\n\n That's equivalent to providing a literal \n\n```\narray\n```\n\n. \n\n```\n
{[
first
,
second
]}
\n```\n\n This pattern can be combined with destructuring, JSX Spread Attributes, and other components, for some serious terseness. \n\n```\n
\n```\n\n Function as children # React components don't support functions as \n\n```\nchildren\n```\n\n. However, render props is a pattern for creating components that take functions as children. Render prop # Here's a component that uses a render callback. It's not useful, but it's an easy illustration to start with. \n\n```\nconst Width = ({ children }) => children(500);\n```\n\n The component calls \n\n```\nchildren\n```\n\n as a function, with some number of arguments. Here, it's the number \n\n```\n500\n```\n\n. To use this component, we give it a function as \n\n```\nchildren\n```\n\n. \n\n```\n{(width) =>
window is {width}
}\n```\n\n We get this output. \n\n```\n
window is 500
\n```\n\n With this setup, we can use this \n\n```\nwidth\n```\n\n to make rendering decisions. \n\n```\n\n {(width) => (width > 600 ?
min-width requirement met!
: null)}\n\n```\n\n If we plan to use this condition a lot, we can define another components to encapsulate the reused logic. \n\n```\nconst MinWidth = ({ width: minWidth, children }) => (\n {(width) => (width > minWidth ? children : null)}\n);\n```\n\n Obviously a static \n\n```\nWidth\n```\n\n component isn't useful but one that watches the browser window is. Here's a sample implementation. \n\n```\nclass WindowWidth extends React.Component {\n constructor() {\n super();\n this.state = { width: 0 };\n }\n componentDidMount() {\n this.setState({ width: window.innerWidth }, () =>\n window.addEventListener(\"resize\", ({ target }) =>\n this.setState({ width: target.innerWidth })\n )\n );\n }\n render() {\n return this.props.children(this.state.width);\n }\n}\n```\n\n Many developers favor Higher Order Components for this type of functionality. It's a matter of preference. Children pass-through # You might create a component designed to apply \n\n```\ncontext\n```\n\n and render its \n\n```\nchildren\n```\n\n. \n\n```\nclass SomeContextProvider extends React.Component {\n getChildContext() {\n return { some: \"context\" };\n }\n render() {\n // how best do we return `children`?\n }\n}\n```\n\n You're faced with a decision. Wrap \n\n```\nchildren\n```\n\n in an extraneous \n\n```\n\n```\n\n or return \n\n```\nchildren\n```\n\n directly. The first options gives you extra markup (which can break some stylesheets). The second will result in unhelpful errors. \n\n```\n// option 1: extra div\nreturn
{children}
;\n// option 2: unhelpful errors\nreturn children;\n```\n\n It's best to treat \n\n```\nchildren\n```\n\n as an opaque data type. React provides \n\n```\nReact.Children\n```\n\n for dealing with \n\n```\nchildren\n```\n\n appropriately. \n\n```\nreturn React.Children.only(this.props.children);\n```\n\n Proxy component # (I'm not sure if this name makes sense) Buttons are everywhere in web apps. And every one of them must have the \n\n```\ntype\n```\n\n attribute set to \"button\". \n\n```\n