Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a className on custom react components? [duplicate]

Let's say I have a simple component like this:

class SimpleComponent extends React.Component {     render() { return <p>Some text</p> } } 

Is it possible to add a className to SimpleComponent or is this constrained to HTML DOM elements only?

For example:

var mySimpleComponent = <SimpleComponent className="myComp"/> 

The reason I would like to do this is so that I can style the elements inside my custom component like this:

.myComp > p {     background-color: blue; } 
like image 508
sookie Avatar asked Sep 04 '17 16:09

sookie


People also ask

Can React components have className?

React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In class-based components, the className attribute is used to set or return the value of an element's class attribute.

Can I use multiple className in React?

We can add a multiple class names to the react element conditionally; by using template literals, ternary operator.

How do you repeat components in React?

To repeat an element n times with React, we can use the Array function with the map array method. to create an array with 8 span elements with the same content by calling the Array with the n to create an empty array with n slots. Then we use the spread operator to make a copy of it.


1 Answers

You can, but you should propagate the prop to the inner component. If not, it doesn't know about it.

class SimpleComponent extends React.Component {     render() { return <p className={this.props.className}>Some text</p> } } 

To make the CSS query you want to accomplish, then you should create the div inside your component.

class SimpleComponent extends React.Component {     render() { return <div className={this.props.className}><p>Some text</p></div> } } 
like image 139
jorgonor Avatar answered Sep 20 '22 17:09

jorgonor