Solve - No duplicate props allowed warning in React

avatar

Borislav Hadzhiev

Last updated: Apr 27, 2022

banner

Check out my new book

Solve - No duplicate props allowed warning in React #

The warning "No duplicate props allowed" is caused when we pass the same prop multiple times to the same component. To solve the warning, make sure to only pass the prop once. For example, if passing multiple className props, concatenate them into a space-separated string.

Here is an example of how the warning is caused.

App.js
const App = () => { // ⛔️ JSX elements cannot have multiple attributes with the same name.ts(17001) // No duplicate props allowed eslintreact/jsx-no-duplicate-props return ( <div> <Button text="Click" text="Submit" /> </div> ); }; function Button({text}) { return <button onClick={() => console.log('button clicked')}>{text}</button>; } export default App;

no duplicate props allowed

The issue in the code snippet is that we're passing the text prop twice to the Button component.

This is not allowed because the second text prop would override the first.

Make sure to only pass each props once to the same component.

App.js
const App = () => { // 👇️ only pass text prop once return ( <div> <Button text="Submit" /> </div> ); }; function Button({text}) { return <button onClick={() => console.log('button clicked')}>{text}</button>; } export default App;

If you got the error when trying to pass multiple className props, you have to concatenate them into a string and pass the prop only once.

App.js
const App = () => { return ( <div> <h2 className="my-class-1 my-class-2 my-class-3">Hello world</h2> </div> ); }; export default App;

Instead of passing multiple className props, we have to pass multiple, space-separated classes in the string we set for the className prop.

If you need to interpolate variables in a string prop, use a template literal.

App.js
const App = () => { const class1 = 'bg-lime'; const class2 = 'text-white'; return ( <div> <h2 className={`padding-3 ${class1} ${class2}`}>Hello world</h2> </div> ); }; export default App;

Note that template literals use backticks ``, and not single quotes.

The expressions in the dollar sign curly braces ${} syntax will get replaced with the actual values of the class1 and class2 variables.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.