Is there a native way to add a style class name to a react element passed as a property WITHOUT using jQuery or any 3rd-party libraries.
The following example should demonstrate what I’m trying to do. Note, react class names are made up.
Edit: The point is to modify the class name of a react element that is passes as a property to the Books class! The Books class needs to modify the class name. Apparently, it does not have access to Authors class’s state to use within Authors class.
File authors.js
class Authors {
render() {
return (
<ul>
<li>John Doe</li>
<li>Jane Doe</li>
</ul>
);
}
}
File shelf.js
class Shelf {
render() {
return (
<div>
<Books authors={<Authors/>}/>
</div>
);
}
}
File books.js
class Books {
this.props.authors.addClass('style-class-name'); <- HERE
render() {
return (
<div>
{this.props.authors}
</div>
);
}
}
2
Answers
Potentially need more context, but in this kind of scenario, I would use state to dynamically add/remove a class. A basic example would be:
The state changes schedule a re-render, hence you end up with dynamic classes depending on the state. Could also pass the class in as a property, or however you want to inject it into the component.
React elements do have an attribute called
className
. You can use that to set CSS classes to your component. You can pass static data (strings) or dynamic ones (basically calculated ones):Keep in mind, that you have to pass down your className, if you wrap native HTML elements in a component:
If you want to add data to your
authors
attribute (which I assume is an array), you could implement a thing like the following:Keep in mind, that either way, you have to manually assign this
className
property in your child components (I guess anAuthor
component)To handle updates from a child component, use functions: https://reactjs.org/docs/faq-functions.html
Full example: