0

I am trying to write a react application where the App component renders an array of components to the screen. But the inline CSS are not showing up.

//App component
import data from "./data.js"
import Item from "./Item"

export default function App(){
   const cardElements = data.map(item => <Item/>)
   return (<div className='app'>
               {cardElements}
           </div>);
}
//Item component
export default function Item(){
   const customStyle = {border: "2px solid black"};
   return (<div style={customStyle} >Item component</div>);
}

The inline CSS in the Item component does not reflect on the webpage.

1 Answer 1

2

As you can see in the snippet below the inline style does indeed work. What is likely happening here is your style is bering overridden but we'd need more information to know for sure.

Sidenote: don't forget to add key prop when using .map in React.

const data = [1, 2, 3, 4];

function App() {
   const cardElements = data.map(item => <Item key={item} />)
   return (
    <div className='app'>
      {cardElements}
    </div>
   );
}

function Item() {
   const customStyle = { border: "2px solid black" };
   return <div style={customStyle}>Item component</div>;
}

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, somehow the inline CSS is being overriden. I have a global .scss file for the overall styling of the website. I guess that is creating the problem.
Still weird because inline specificity is very high, use developer tools to see where the style is being applied or not @AbhijeetGautam

Your Answer

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

See similar questions with these tags.