React Render Component from Variable

I have often found myself in situations where I needed to decide which component to show on the fly.

Whether I was building a custom dashboard for a New York-based fintech firm or a dynamic form for a Texas healthcare provider, hardcoding components wasn’t an option.

Rendering a component from a variable is one of those “aha!” moments for many developers. It turns your static layouts into truly flexible interfaces.

In this tutorial, I will show you exactly how to store components in variables and render them efficiently in your React projects.

Why Render Components from Variables?

In the early days of my career, I used to write massive, messy switch statements inside my JSX. It was a nightmare to maintain.

By using variables to hold your components, you keep your return statement clean and readable.

This approach is incredibly useful when dealing with dynamic layouts, such as displaying different US state tax forms based on a user’s selection.

Method 1: The Capitalized Variable Approach

The easiest way to render a component from a variable is to assign the component to a variable that starts with a capital letter.

React’s JSX transformer treats lowercase tags (like <div>) as HTML and capitalized tags (like <MyComponent />) as React components.

In this example, let’s imagine we are building a simple “City Explorer” app for tourists visiting popular US destinations.

import React from 'react';

// A simple component for New York City
const NewYorkCity = () => (
  <div style={{ padding: '20px', border: '1px solid #00356B' }}>
    <h2>Welcome to the Big Apple!</h2>
    <p>Don't miss the Statue of Liberty and Central Park.</p>
  </div>
);

// A simple component for Los Angeles
const Los Angeles = () => (
  <div style={{ padding: '20px', border: '1px solid #FFD100' }}>
    <h2>Welcome to the City of Angels!</h2>
    <p>Check out the Hollywood Sign and Santa Monica Pier.</p>
  </div>
);

const CityRenderer = () => {
  // We assign the component itself to a variable
  // Note: The variable name MUST start with a capital letter
  const SelectedCity = Math.random() > 0.5 ? NewYorkCity : LosAngeles;

  return (
    <div style={{ fontFamily: 'Arial, sans-serif', maxWidth: '600px' }}>
      <h1>US Travel Guide</h1>
      <p>Today's featured destination:</p>
      
      {/* We render it just like a regular component */}
      <SelectedCity />
    </div>
  );
};

export default CityRenderer;

I executed the above example code and added the screenshot below.

React Render Component from Variable

When I first started using this, I often forgot the capitalization rule. If you use selectedCity (lowercase), React will try to find an HTML element named <selectedcity>, which doesn’t exist.

Method 2: Use an Object Map for Dynamic Selection

When you have more than two options, using a ternary operator becomes messy. I prefer using a JavaScript object to map keys to components.

This is a pattern I used frequently when building a “Vehicle Registration” portal where different forms were needed for “Sedans,” “Trucks,” and “Motorcycles.”

import React, { useState } from 'react';

// Component for Sedan registration
const SedanForm = () => (
  <div className="form-box">
    <h3>Sedan Registration (Standard)</h3>
    <label>License Plate: <input type="text" placeholder="ABC-1234" /></label>
  </div>
);

// Component for Truck registration
const TruckForm = () => (
  <div className="form-box">
    <h3>Commercial Truck Registration</h3>
    <label>GVWR Weight: <input type="number" placeholder="10000" /></label>
  </div>
);

// Component for Motorcycle registration
const MotorcycleForm = () => (
  <div className="form-box">
    <h3>Motorcycle Registration</h3>
    <label>Sidecar attached? <input type="checkbox" /></label>
  </div>
);

// The Mapper Object
const VEHICLE_COMPONENTS = {
  sedan: SedanForm,
  truck: TruckForm,
  motorcycle: MotorcycleForm
};

const RegistrationPortal = () => {
  const [vehicleType, setVehicleType] = useState('sedan');

  // We look up the component based on the state string
  const SpecificForm = VEHICLE_COMPONENTS[vehicleType];

  return (
    <div style={{ padding: '40px', backgroundColor: '#f4f4f4' }}>
      <h2>Department of Motor Vehicles (DMV)</h2>
      <p>Select your vehicle type to begin:</p>
      
      <select value={vehicleType} onChange={(e) => setVehicleType(e.target.value)}>
        <option value="sedan">Sedan</option>
        <option value="truck">Truck</option>
        <option value="motorcycle">Motorcycle</option>
      </select>

      <hr />

      {/* Render the dynamically selected component */}
      {SpecificForm ? <SpecificForm /> : <p>Please select a vehicle.</p>}
    </div>
  );
};

export default RegistrationPortal;

I executed the above example code and added the screenshot below.

Render Component from Variable React

In my experience, this is the cleanest way to handle dynamic UIs. It separates your logic (the mapping) from your presentation (the JSX).

Method 3: Pass Components via Props

Sometimes, the “variable” holding the component isn’t local; it’s passed down from a parent component.

Think of a “Generic Card” component used across a real estate website. You might want to pass a “Luxury Badge” component to some cards but not others.

import React from 'react';

// A reusable Card component that accepts a component as a prop
const PropertyCard = ({ address, price, BadgeComponent }) => {
  return (
    <div style={{ border: '1px solid #ccc', margin: '10px', padding: '15px', borderRadius: '8px' }}>
      {/* If a BadgeComponent is provided, render it */}
      {BadgeComponent && <BadgeComponent />}
      
      <h3>{address}</h3>
      <p>Listing Price: {price}</p>
      <button>View Details</button>
    </div>
  );
};

// A specific badge component
const FeaturedBadge = () => (
  <span style={{ background: 'gold', padding: '2px 5px', fontSize: '12px', fontWeight: 'bold' }}>
    FEATURED LISTING
  </span>
);

const RealEstateApp = () => {
  return (
    <div>
      <h1>Chicago Real Estate Listings</h1>
      
      {/* Example 1: Passing the component variable as a prop */}
      <PropertyCard 
        address="123 Michigan Ave, Chicago, IL" 
        price="$1,200,000" 
        BadgeComponent={FeaturedBadge} 
      />

      {/* Example 2: No badge component passed */}
      <PropertyCard 
        address="456 Oak St, Evanston, IL" 
        price="$450,000" 
      />
    </div>
  );
};

export default RealEstateApp;

I executed the above example code and added the screenshot below.

Render Component from Variable in React

Notice that I pass FeaturedBadge (the reference) rather than <FeaturedBadge /> (the invoked element). This gives the child component control over how and when to render it.

Common Issues to Avoid

I have seen many junior developers struggle with two main issues when rendering components from variables.

First, as mentioned before, case sensitivity is vital. React will ignore const myComp = … if you try to use <myComp />.

Second, be careful with infinite loops. If you define a component inside the render body of another component, React will recreate it on every render, losing state and focus.

Always define your sub-components outside the main function or memoize them if they must be dynamic.

Handle Props with Dynamic Components

When your variable-based component needs its own props, you can pass them just like any other component.

Suppose you are building a “US Presidential Election” tracker where different candidate components need specific data.

The Full Code Example

import React from 'react';

const CandidateProfile = ({ name, party, electoralVotes }) => (
  <div style={{ padding: '10px', margin: '10px', backgroundColor: party === 'Blue' ? '#d1e9ff' : '#ffd1d1' }}>
    <h3>{name}</h3>
    <p>Party: {party}</p>
    <p>Electoral Votes: {electoralVotes}</p>
  </div>
);

const ElectionDashboard = () => {
  const ActiveView = CandidateProfile;

  return (
    <div>
      <h2>2024 Election Insights</h2>
      
      {/* Passing props to the variable component */}
      <ActiveView name="John Doe" party="Blue" electoralVotes={210} />
      <ActiveView name="Jane Smith" party="Red" electoralVotes={195} />
    </div>
  );
};

export default ElectionDashboard;

This flexibility allows you to swap out the entire UI structure while keeping the data flow consistent.

When to Use “Render Functions” Instead

Sometimes, storing a component in a variable is overkill. If the logic is very simple, I often use a “Render Function.”

This is a local function that returns JSX. It’s a great way to break up a large component into smaller, manageable chunks without creating entirely new files.

import React from 'react';

const WeatherDashboard = () => {
  const weatherType = "Snowy"; // Imagine this comes from an API

  // A render function acting as a dynamic variable
  const renderWeatherAlert = () => {
    switch (weatherType) {
      case "Sunny":
        return <p>It's a beautiful day in Miami! Wear sunscreen.</p>;
      case "Snowy":
        return <p>Heavy snow in Buffalo. Please stay off the roads.</p>;
      default:
        return <p>Check your local US forecast for updates.</p>;
    }
  };

  return (
    <div style={{ textAlign: 'center', padding: '50px' }}>
      <h1>National Weather Service</h1>
      <div className="alert-box">
        {renderWeatherAlert()}
      </div>
    </div>
  );
};

export default WeatherDashboard;

I find this approach helpful for small UI components tightly coupled to the component’s local state.

I hope you found this guide on rendering React components from variables useful.

I have used these techniques in countless production apps to create flexible and maintainable codebases. Whether you use a simple variable, an object map, or pass components as props, you now have the tools to build more dynamic React applications.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.