Trí Phan
Trí Phan

Reputation: 1193

Change the style of the react component based on its props

I have a Header.js:

const Header = () => {
 return (
  <header className="header">
    <Logo/>
    <HeaderMenu target="home-link"/>
  </header>);
}

and a HeaderMenu.js:

class HeaderMenu extends React.Component {
 render() {
    return(
        <nav className="header-menu">
            <a id="home-link">Home</a>
            <a id="project-link">Projects</a>
            <a id="blog-link">Blog</a>
            <a id="about-me-link">About Me</a>
        </nav>
    );
 }
}

How can I change an a elements style based on target props?
Example: if target="home-link", then an a element with id="home-link" has its text underlined and another a element doesn't.

Upvotes: 0

Views: 70

Answers (2)

atool
atool

Reputation: 496

  1. Save menu data into an variable.
  2. Use map to add a tag
  3. Set an className = 'active' on the a where target is matched.
  4. then write css to add underline.

HeaderMenu.js

class HeaderMenu extends React.Component {

 constructor(props) {
     super(props);
     this.menus = [
       { id: 'home-link', name: 'Home' },
       { id: 'project-link', name: 'Projests' },
       // ...
     ];
}

 render() {
    return(
        <nav className="header-menu">
            {
              this.menus.map(menu => (<a id={menu.id} className={this.props.target === menu.id ? 'active' : ''}>{menu.name}</a>))
            }
        </nav>
    );
 }

}

css:

.active {
   // text style when active
}

Upvotes: 0

Henry Woody
Henry Woody

Reputation: 15662

You can do this by applying a class to any element that you want to have styled differently. In your example of giving a different style to the link for the current page, you can iterate over your links and give an "active" class to the link whose id matches the target.

For Example:

class HeaderMenu extends React.Component {
 render() {
    const { target } = this.props;

    const linkData = [
        {id: "home-link", title: "Home"},
        {id: "project-link", title: "Projects"},
        {id: "blog-link", title: "Blog"},
        {id: "about-me-link", title: "About Me"},
    ];
    const linkElements = linkNames.map(e => (
        <a id={ e.id } className={ e.id === target ? "active" : "" }>{ e.title }</a>
    ));

    return(
        <nav className="header-menu">
            { linkElements }
        </nav>
    );
 }
}

However if you use React Router (which you may want to do so the page doesn't refresh when a link is clicked) the <NavLink> component takes an activeClassName prop, which applies the given className any time the current location (url) matches the NavLink's to prop (which is analogous to the a tag's href).

Upvotes: 2

Related Questions