Aller au contenu

React et les styles

Styled-components

  • CSS dans le code JavaScript pour laisser React créer les fichiers css.
  • Fini les erreurs css lorsqu’on utilise le même nom de classe par erreur.

Pour l’installer dans votre projet :

console
npm i styled-components
npm i @types/styled-components --save-dev

Remplacer le css par un fichier tsx

personnage.styles.tsx
import styled from 'styled-components';

export const PersonnageContainer = styled.div`
  max-width: 400px;
  width: 300px;
  margin: 0 auto;
  background-color: #fff;
  color: #000;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
`;

export const PersonnagePhoto = styled.div`
  text-align: center;
  margin-bottom: 20px;
`;

export const PersonnageImage = styled.img`
  width: 150px;
  height: 150px;
  border-radius: 50%;
`;

export const PersonnageInfo = styled.div`
  margin-bottom: 20px;
`;

export const PersonnageAddress = styled.p`
  font-style: italic;
`;
personnage.component.tsx
import {
  PersonnageContainer,
  PersonnageAddress,
  PersonnageImage,
  PersonnageInfo,
  PersonnagePhoto,
} from './personnage.styles';

interface IPersonnageProps {
  nom: string;
  photo: string;
  adresse: string;
}

const Personnage = (props: IPersonnageProps) => {
  return (
    <PersonnageContainer>
      <PersonnagePhoto>
        <PersonnageImage src={props.photo} />
      </PersonnagePhoto>
      <PersonnageInfo>
        <PersonnageAddress as="span">{props.nom}</PersonnageAddress>
        <PersonnageAddress>{props.adresse}</PersonnageAddress>
      </PersonnageInfo>
    </PersonnageContainer>
  );
};

export default Personnage;

Truc

Utilisation d’un style pour un autre type d’élément HTML avec la mention as :

<PersonnageAddress as="span">{props.nom}</PersonnageAddress>

Material UI

Librairie de composantes pré-stylisées.

Pour l’installer dans votre projet :

console
npm i @mui/material @emotion/react @emotion/styled
npm i @fontsource/roboto
npm install @mui/icons-material

Utiliser Material UI

personnage.component.tsx
import Card from '@mui/material/Card';
import CardMedia from '@mui/material/CardMedia';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { Grid } from '@mui/material';

interface IPersonnageProps {
  nom: string;
  photo: string;
  adresse: string;
}

const Personnage = (props: IPersonnageProps) => {
  return (
    <Card sx={{ width: 400 }}>
      <Grid container spacing={0} direction="column" alignItems="center">
        <CardMedia
          image={props.photo}
          sx={{ height: 150, width: 150, borderRadius: '50%' }}
        />
      </Grid>
      <Box>
        <Typography variant="subtitle1">{props.nom}</Typography>
        <Typography variant="subtitle1">{props.adresse}</Typography>
      </Box>
    </Card>
  );
};

export default Personnage;

CodeSandbox

Démo - Material UI

Thèmes dans Material UI

La manière la plus efficace pour changer l'apparence de votre application avec Material UI est l'utilisation de thèmes.

La place idéale pour ajouter un thème à votre application est App.tsx :

app.tsx
import Personnage from './components/personnage.component';
import { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [nom, setNom] = useState('');
  const [longueurNom, setLongueurNom] = useState(0);

  useEffect(() => {
    setLongueurNom(nom.length);
  }, [nom]);

  const nomDuPersonnage = 'Fluffy McChat';
  const photoDuPersonnage = 'https://placekitten.com/300/300';
  const adresseDuPersonnage = '123 Ave Des Félins';

  return (
    <>
      <input value={nom} onChange={(e) => setNom(e.target.value)} />
      <span>Le nom a {longueurNom} caractères</span>
      <Personnage
        nom={nomDuPersonnage}
        photo={photoDuPersonnage}
        adresse={adresseDuPersonnage}
      />
      <Personnage
        nom={nom}
        photo="https://placekitten.com/300/300"
        adresse="444 de le Bête"
      />
    </>
  );
}

export default App;

Vous pouvez aussi assigner une apparence spécifiquement à un type de composant comme suit :

app.tsx
components: {
    MuiButton: {
      styleOverrides: {
        root: {
          backgroundColor: '#172325 ',
          color: '#007AFF',
          primary: '#FFFFFF',
          ':hover': {
            color: '#5C5757',
          },
        },
      },
    },
  },