React - Dimensões de tela
Este é meu primeiro post sobre React e trarei uma série de dicas e truques que facilitam o dia a dia.
Este exemplo mostra como obter as dimensões da janela dinâmicas ouvindo o redimensionamento do navegador para manter o valor no estado do componente.
Nível: Básico
Dificuldade: Baixa
Farei o exemplo dentro da Classe APP para facilitar mas você pode colocar em qualquer componente.
Passos:
1. Crie os states: windowHeight e windowWidth
this.state = { windowHeight: 0, windowWidth: 0 };
2. Crie o método updateWindowDimensions
updateWindowDimensions() {
this.setState({ windowWidth: window.innerWidth,
windowHeight: window.innerHeight });
}
3. Faça o bind deste método criado no contrutor:
constructor() {
super();
this.state = {
windowHeight: 0,
windowWidth: 0
};
this.updateWindowDimensions =
this.updateWindowDimensions.bind(this);
}
4. Crie o método componentDidMount que chama o método criado no step 2 e também cria um evento de para escutar o m''etodo de update
window.addEventListener('resize', this.updateWindowDimensions);
Este é meu primeiro post sobre React e trarei uma série de dicas e truques que facilitam o dia a dia.
Nível: Básico
this.setState({ windowWidth: window.innerWidth,
windowHeight: window.innerHeight });
}
constructor() {
super();
this.state = {
windowHeight: 0,
windowWidth: 0
};
this.updateWindowDimensions =
this.updateWindowDimensions.bind(this);
}
5. Crie o método componentWillUnmount que remove o listener:
componentWillUnmount() {
window.removeEventListener('resize',
this.updateWindowDimensions);
}
Pronto e como exemplo criei 2 divs com estilos inline que são dinâmicamente alteradas de acordo com a largura de tela:
<div style={{
width: this.state.windowWidth >= 431 ? '100%' : '50%' ,
backgroundColor:
this.state.windowWidth >= 431 ? 'blue' : 'green'
}}>
Content 1
</div>
<div style={{
width: this.state.windowWidth < 431 ? '100%' : '50%' ,
backgroundColor:
this.state.windowWidth < 431 ? 'red' : 'pink'
}}>
Content 2
</div>
componentWillUnmount() {
window.removeEventListener('resize',
this.updateWindowDimensions);
}
<div style={{
width: this.state.windowWidth >= 431 ? '100%' : '50%' ,
backgroundColor:
this.state.windowWidth >= 431 ? 'blue' : 'green'
}}>
Content 1
</div>
<div style={{
width: this.state.windowWidth < 431 ? '100%' : '50%' ,
backgroundColor:
this.state.windowWidth < 431 ? 'red' : 'pink'
}}>
Content 2
</div>
O código final encontra-se abaixo e neste link
afs-react-window-dimensions - StackBlitz
Starter project for React apps that exports to the create-react-app CLI.
Menor que 431
Maior
Menor que 431afs-react-window-dimensions - StackBlitz
Starter project for React apps that exports to the create-react-app CLI.
Comentários
Postar um comentário