Home > OS >  React tailwind, cannot pass tailwind css from parent to child
React tailwind, cannot pass tailwind css from parent to child

Time:01-25

I am running into a simple issue that doesn't seem to have an answer on quick google search or Tailwind doc.

I am a Vuejs user but I have started learning React. I have opted to use TailwindCSS for testing my React application but I noticed there is some differences of Tailwind usage between Vuejs and React.

In Vue, I can control a child component via the parent component like so:

Parent component:
<template>
 <div >
  <ChildComponent  />
 </div>
</template>

With the child being able to centre on screen through the above parent component as should in the ChildComponent's class.

However, when I tried to do the same in React like so:

Parent component:
import Homepage from './views/Homepage';

function App() {
  return (
    <div className='bg-black w-screen'>
      <Homepage className="w-1/2 mx-auto"/>
    </div>
  );
}

export default App;

Nothin happens when I placed the CSS at the Homepage child component from the parent.

I am sure there is a simple answer but I wasn't about to search the doc or use any keywords to find this problem. Anyone got a hint or confirm this is intended in React or have I done something wrong with the installation?

CodePudding user response:

You need to consider that <Homepage/> is a React component and cannot accept HTMLAttrs just like that. this example might clear it:

const app = () => {
    <div className="bg-black">
        <Homepage className="bg-red" />
    </div>
}
const homePage = (props) => {
    <div className={props.className}>
        <h1 className="bg-red">hi</h1>
    </div>
}

the className that you pass to <Homepage/> is actually a props rather than Html attribure.

CodePudding user response:

This is less of a Tailwind question and more of a React question. You cannot use className on the Homepage component without passing it as a prop. In your case, Homepage is not expecting any className. So while making your Homepage component you have to provide a prop called 'className' then it will work fine. Or if you simply use a div in place of Homepage it will work normally. Have a look at this codesandbox link

  •  Tags:  
  • Related