eclipsis eclipsis - 3 months ago 12
React JSX Question

React: Show 1st child/hide 2nd child when link is not active, hide 1st child/show 2nd child when link is active?

I have 2 links with 2 children each, that both need to show their 1st child/hide their 2nd child when the parent link is not active, and then hide the 1st child/show the 2nd child when the parent link is active. How could I accomplish this within React?

<Link activeClassName="active" className="sidebar-link" to="/tech/link1">
<span className="collapsed">
Title
</span>
<div className="expanded">
Content
</div>
</Link>

<Link activeClassName="active" className="sidebar-link" to="/tech/link2">
<span className="collapsed">
Title
</span>
<div className="expanded">
Content
</div>
</Link>

Answer

Simple way is to render link content depending on state.

In the render just render on a if like:

  {/* only rendered if activeMenuId === 2 */}
   {
     activeMenuId === 2 &&
     <span className="collapsed">
       Title
     </span>
   } 
   {/* only rendered if activeMenuId === 1 */}
   {
     activeMenuId === 1 &&
     <div className="expanded">
       Content
     </div>
   } 

More code to illustrate what I mean:

import React, { Component } from 'react';
import { Link } from 'react-router';

class demo extends Component {
 constructor(props) {
   super(props);
   this.state = {
     activeMenuId: 1 // assuming at least 1 menu active
   };
 }
  
 render() {
  const { activeMenuId } = this.state; // destructuring helps for readability see below
   
  return (
    <div>
      {/* first menu */}
      <Link 
        activeClassName={activeMenuId === 1 ? 'active' : ''}
        className="sidebar-link" 
        to="/tech/link1">
    
        {/* only visible if menuId = 1 is active */}
        {
          activeMenuId === 1 &&
          <span className="collapsed">
            Title
          </span>    
        }
    
        {/* only visible if menuId= 2 is active */}
        {
          activeMenuId === 2 &&
          <div className="expanded">
            Content
          </div>
        }    
      </Link>

     {/* second menu */}
     <Link 
       activeClassName={activeMenuId === 2 ? 'active' : ''}   
       className="sidebar-link" 
       to="/tech/link2">
       {/* only visible if menuId = 1 is active */}
       {
         activeMenuId === 2 &&
         <span className="collapsed">
           Title
         </span>
       } 
       {/* only visible if menuId= 1 is active */}
       {
         activeMenuId === 1 &&
         <div className="expanded">
           Content
         </div>
       }        
      </Link>
    </div>
  )
 }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Comments