In this article, we will explore the use of React Hooks by creating various functional components for a SharePoint Framework (SPFx) project. We’ll walk through the full code for integrating these components into the main TSX file (ControlesBasicos.tsx), ensuring everything is clear and organized.


Mastering React Hooks in SPFx: 10 Practical Examples for Web Parts

In this article, we will explore the use of React Hooks by creating various functional components for a SharePoint Framework (SPFx) project. We’ll walk through the full code for integrating these components into the main TSX file (ControlesBasicos.tsx), ensuring everything is clear and organized.


1. Counter Component

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Counter: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};

export default Counter;

2. ToggleText Component

import React, { useState } from 'react';

const ToggleText = () => {
  const [isVisible, setIsVisible] = useState(true);

  return (
    <div>
      <h2>{isVisible ? 'Hello, World!' : ''}</h2>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? 'Hide' : 'Show'} Text
      </button>
    </div>
  );
};

export default ToggleText;

3. ClickCounter Component

import React, { useState } from 'react';

const ClickCounter = () => {
  const [clicks, setClicks] = useState(0);

  return (
    <div>
      <h2>Button Clicked {clicks} times</h2>
      <button onClick={() => setClicks(clicks + 1)}>Click Me!</button>
    </div>
  );
};

export default ClickCounter;

4. BackgroundChanger Component

import React, { useState } from 'react';

const BackgroundChanger = () => {
  const [color, setColor] = useState('#f3f3f3');

  return (
    <div style={{ backgroundColor: color, padding: '20px' }}>
      <h2>Background Color Changer</h2>
      <button onClick={() => setColor('#a29bfe')}>Change to Blue</button>
      <button onClick={() => setColor('#fdcb6e')}>Change to Yellow</button>
    </div>
  );
};

export default BackgroundChanger;

5. TextInput Component

import React, { useState } from 'react';

const TextInput = () => {
  const [text, setText] = useState('');

  return (
    <div>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something..."
      />
      <h3>You typed: {text}</h3>
    </div>
  );
};

export default TextInput;

6. Countdown Component

import React, { useState, useEffect } from 'react';

const Countdown = () => {
  const [count, setCount] = useState(10);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount((prevCount) => (prevCount > 0 ? prevCount - 1 : 0));
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return (
    <div>
      <h2>Countdown: {count}</h2>
    </div>
  );
};

export default Countdown;

7. DarkModeToggle Component

import React, { useState } from 'react';

const DarkModeToggle = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);

  return (
    <div style={{ backgroundColor: isDarkMode ? '#333' : '#fff', color: isDarkMode ? '#fff' : '#000', padding: '20px' }}>
      <h2>{isDarkMode ? 'Dark Mode' : 'Light Mode'}</h2>
      <button onClick={() => setIsDarkMode(!isDarkMode)}>
        Toggle Dark Mode
      </button>
    </div>
  );
};

export default DarkModeToggle;

8. TabComponent

import React, { useState } from 'react';

const TabComponent = () => {
  const [activeTab, setActiveTab] = useState('Tab1');

  return (
    <div>
      <button onClick={() => setActiveTab('Tab1')}>Tab 1</button>
      <button onClick={() => setActiveTab('Tab2')}>Tab 2</button>

      {activeTab === 'Tab1' ? <h2>Content of Tab 1</h2> : <h2>Content of Tab 2</h2>}
    </div>
  );
};

export default TabComponent;

9. Stopwatch Component

import React, { useState, useEffect } from 'react';

const Stopwatch = () => {
  const [time, setTime] = useState(0);
  const [isActive, setIsActive] = useState(false);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (isActive) {
      interval = setInterval(() => {
        setTime((prevTime) => prevTime + 1);
      }, 1000);
    } else if (!isActive && time !== 0) {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isActive, time]);

  return (
    <div>
      <h2>Stopwatch: {time}s</h2>
      <button onClick={() => setIsActive(!isActive)}>{isActive ? 'Pause' : 'Start'}</button>
      <button onClick={() => setTime(0)}>Reset</button>
    </div>
  );
};

export default Stopwatch;

10. ThemeSelector Component

import React, { useState } from 'react';

const ThemeSelector = () => {
  const [theme, setTheme] = useState('light');

  return (
    <div style={{ backgroundColor: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff', padding: '20px' }}>
      <h2>{theme.charAt(0).toUpperCase() + theme.slice(1)} Theme</h2>
      <button onClick={() => setTheme('light')}>Light Theme</button>
      <button onClick={() => setTheme('dark')}>Dark Theme</button>
    </div>
  );
};

export default ThemeSelector;

Putting It All Together: The Main Component

Once the individual components are created, here’s how you can integrate them into the main file ControlesBasicos.tsx:

import * as React from 'react';

import Counter from './Counter';
import ToggleText from './ToggleText';
import ClickCounter from './ClickCounter';
import BackgroundChanger from './BackgroundChanger';
import TextInput from './TextInput';
import Countdown from './Countdown';
import DarkModeToggle from './DarkModeToggle';
import TabComponent from './TabComponent';
import Stopwatch from './Stopwatch';
import ThemeSelector from './ThemeSelector';

const ControlesBasicos = () => {
  return (
    <div>
      <div style={{ backgroundColor: "#E5E4E2", padding: '20px' }}>React Hooks - SPFx Study Sheet</div>
      <hr />
      <Counter />
      <hr />
      <ToggleText />
      <hr />
      <ClickCounter />
      <hr />
      <BackgroundChanger />
      <hr />
      <TextInput />
      <hr />
      <Countdown />
      <hr />
      <DarkModeToggle />
      <hr />
      <TabComponent />
      <hr />
      <Stopwatch />
      <hr />
      <ThemeSelector />
      <hr />
    </div>
  );
};

export default ControlesBasicos;

Conclusion

We walked through 10 React components using hooks and demonstrated how to integrate them into an SPFx Web Part. These examples serve as practical exercises to help you deepen your understanding of React state management and component interaction.

Stay tuned for more advanced tutorials as we dive deeper into building dynamic user interfaces in SPFx

Edvaldo Guimrães Filho Avatar

Published by

Categories:

Leave a comment