Home > database >  Want to Render component according to button
Want to Render component according to button

Time:11-02

I want to render component according to the input. Here i made a function that returns the component according to the input but it not showing anything.I used ant css framework.This is a sorting visualizer code . Here first i am showing the sorting visulizer and then about the algorithm and its time complexity and space complexity. Instead of making new page i want to render a component that changes according to the input. My logic is coorect but it showing nothing.

import React, { useState } from 'react';
import selectionSort from '../../algorithms/selection-sort';
import generateRandomizedArray from '../../helpers/randomizeArray';
import SortingBar from '../SortingBar/SortingBar';
import HomeHeader from '../HomeHeader/HomeHeader';
import '../../index.css';
import bubbleSort from '../../algorithms/bubble-sort';
import insertionSort from '../../algorithms/insertion-sort';
import mergeSortWrapper from '../../algorithms/merge-sort';
import quickSortLWrapper from '../../algorithms/quick-sort-l';
import countingSort from '../../algorithms/counting-sort';
import radixSort from '../../algorithms/radix-sort';
import heapSort from '../../algorithms/heap-sort';
import CodeEditor from '../CodeEdior/CodeEditor';
import {Routes,Route} from 'react-router-dom';

const Home = () => {
  const arraySize = 100;
  const [isVisualizing, setIsVisualizing] = useState(false);
  const [randomizedArray, setRandomizedArray] = useState(
    generateRandomizedArray({ arraySize: arraySize })
  );
  const [colorsArray, setColorsArray] = useState(
    new Array(randomizedArray.length).fill(0)
  );
  const [visualizationSpeed, setVisualizationSpeed] = useState(30);
  const [maxItem, setMaxItem] = useState(Math.max(...randomizedArray));
  const [currentAlgorithm, setCurrentAlgorithm] = useState('Bubble Sort');
  const algorithms = [
    'Bubble Sort',
    'Insertion Sort',
    'Selection Sort',
    'QuickSort',
    'Merge Sort',
    'Counting Sort',
    'Radix Sort',
    'Heap Sort'
  ];

  const codeEditor = ({algo}) => {
    switch(algo){
      case"Bubble Sort":
        return <CodeEditor/>
      default:
        break;
    }
  }

  const onRandomize = () => {
    if (isVisualizing) return;
    const nextRandomizedArray = generateRandomizedArray({
      arraySize: randomizedArray.length,
    });
    setRandomizedArray(nextRandomizedArray);
    setMaxItem(Math.max(...nextRandomizedArray));
  };
  const onInputSizeChanged = (val) => {
    if (isVisualizing) return;
    const nextRandomizedArray = generateRandomizedArray({ arraySize: val });
    setRandomizedArray(nextRandomizedArray);
    setMaxItem(Math.max(...nextRandomizedArray));
    setColorsArray(new Array(nextRandomizedArray.length).fill(0));
  };
  const onSpeedChange = (val) => {
    if (isVisualizing) return;
    setVisualizationSpeed(100 - val   1);
  };

  const onVisualize = async () => {
    if (isVisualizing) return;

    setIsVisualizing(true);
    switch (currentAlgorithm) {
      case 'Selection Sort':
        await selectionSort({
          array: randomizedArray,
          setArray: setRandomizedArray,
          visualizationSpeed: visualizationSpeed,
          setColorsArray: setColorsArray,
        });
        break;

      case 'Bubble Sort':
        await bubbleSort({
          array: randomizedArray,
          setArray: setRandomizedArray,
          visualizationSpeed: visualizationSpeed,
          setColorsArray: setColorsArray,
        });
        break;

      case 'Insertion Sort':
        await insertionSort({
          array: randomizedArray,
          setArray: setRandomizedArray,
          visualizationSpeed: visualizationSpeed,
          setColorsArray: setColorsArray,
        });
        break;

      case 'QuickSort':
        await quickSortLWrapper({
          array: randomizedArray,
          leftIndex: 0,
          rightIndex: randomizedArray.length - 1,
          setArray: setRandomizedArray,
          visualizationSpeed: visualizationSpeed,
          setColorsArray: setColorsArray,
        });
        break;
      
      case 'Merge Sort':
        await mergeSortWrapper({
          array: randomizedArray,
          leftIndex: 0,
          rightIndex: randomizedArray.length - 1,
          setArray: setRandomizedArray,
          visualizationSpeed: visualizationSpeed,
          setColorsArray: setColorsArray,
        });
        break;
      case 'Counting Sort':
        await countingSort({
          array:randomizedArray,
          setArray:setRandomizedArray,
          visualizationSpeed:visualizationSpeed,
          setColorsArray:setColorsArray
        });
        break;
        case 'Radix Sort':
        await radixSort({
          array:randomizedArray,
          setArray:setRandomizedArray,
          visualizationSpeed:visualizationSpeed,
          setColorsArray:setColorsArray
        });
        break;
        case 'Heap Sort':
        await heapSort({
          array:randomizedArray,
          setArray:setRandomizedArray,
          visualizationSpeed:visualizationSpeed,
          setColorsArray:setColorsArray
        });
        break;

      default:
        break;
    }

    setIsVisualizing(false);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
      <HomeHeader
        algorithms={algorithms}
        onAlgorithmChange={setCurrentAlgorithm}
        currentAlgorithm={currentAlgorithm}
        onRandomize={onRandomize}
        onInputSizeChanged={onInputSizeChanged}
        onSpeedChange={onSpeedChange}
        onStart={onVisualize}
        isVisualizing={isVisualizing}
      />
      <div
        style={{
          backgroundColor: '#0D1929',
          display: 'flex',
          height: '100%',
          width: '100vw',
          flexDirection: 'row',
          alignItems: 'end',
          padding: '0px 0px 0px 0px',
        }}
      >
        {randomizedArray.map((item, index) => {
          const height = (item / maxItem) * 100;
          const width = (1 / randomizedArray.length) * 100;
          return (
            <div
              key={index}
              style={{
                height: '100%',
                display: 'flex',
                alignItems: 'end',
                width: `${width}%`,
              }}
            >
              <SortingBar
                colorCode={colorsArray[index]}
                style={{
                  height: `calc(${height}% - 20px)`,
                  width: '100%',
                  margin: 'auto 10% 0 10%',
                }}
              ></SortingBar>
            </div>
          );
        })}
        { codeEditor(currentAlgorithm)}
        {/* insert here */}
      </div>
    </div>
  );
};

export default Home;

This is my codeEditor Component

import { Collapse, Space } from 'antd';
import React from 'react';
const { Panel } = Collapse;
const text = `
  A dog is a type of domesticated animal.
  Known for its loyalty and faithfulness,
  it can be found as a welcome guest in many households across the world.
`;
export default function CodeEditor() {
  return (
    <Space direction="vertical" style={{marginLeft:'auto', marginRight:'auto', marginTop:'20px',marginDown:'20px'}}>
    <Collapse collapsible="icon" defaultActiveKey={['1']}>
      <Panel header="This panel can only be collapsed by clicking icon" key="1">
        <p>{text}</p>
      </Panel>
    </Collapse>
  </Space>
  )
}

CodePudding user response:

You have two problems in your code:

  1. You try to destructure the state (currentAlgorithm) although it's a string.
  2. You don't return the rendered component.

Note: You don't need to break after a return statement.

const { useState } = React;

const CodeEditor = () => '<CodeEditor/>';

// don't destructure algo
const codeEditor = (algo) => {
  switch(algo){
    case"Bubble Sort":
      return <CodeEditor/> // return 
    default:
      break;
  }
}

const Demo = () => {
  const [currentAlgorithm, setCurrentAlgorithm] = useState('Bubble Sort');
  return (
    <div>
    {codeEditor(currentAlgorithm)}
    </div>
  );
}

ReactDOM
  .createRoot(root)
  .render(<Demo />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>

Another option is to convert codeEditor to a component (EditorSelector), and render it like a standard component, and pass the props via the selector:

const { useState } = React;

const CodeEditor = ({ val }) => (
  <div>
    value: {val}
  </div>
);

const EditorSelector = ({ algo, ...props }) => {
  console.log(algo);
  switch(algo){
    case"Bubble Sort":
      return <CodeEditor {...props} />;
    default:
      return null;
  }
}

const Demo = () => {
  const [currentAlgorithm, setCurrentAlgorithm] = useState('Bubble Sort');
  return (
    <div>
      <EditorSelector algo={currentAlgorithm} val={1} />
    </div>
  );
}

ReactDOM
  .createRoot(root)
  .render(<Demo />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>

  • Related