How to give padding to items from parent in react - css

I'm using css-module to style react , i have a css file like this
.button-style {
flex-direction: row;
padding: 10px;
}
And an simple react file like this
import React from "react"
import { useEffect, useState, useCallback, useMemo } from "react"
import style from "./styleHook.module.css"
export default function TestEffect() {
const [count, setCount] = useState(1)
const [color, setColor] = useState("black")
const increaseCount = () => setCount(count + 1)
const double = (count: number) => count * 2
const changeColor = (color: string) => {
console.log("uh oh,this will re-render")
color === "black" ? setColor("blue") : setColor("black")
}
useEffect(() => {
console.log("hey count just change and i show up")
}, [count])
return (
<div>
<h1>Value of double count : {count}</h1>
<h2 style={{ color: color }}>This text have {color} color!</h2>
<div className={style['button-style']}>
<button
onClick={() => {
setCount(count + 1)
}}
>
Change value
</button>
<button
onClick={() => {
changeColor(color)
}}
>
Change color
</button>
<button onClick={increaseCount}>Increase count by 1</button>
</div>
</div>
)
}
Now i want to give some space between button, but don't know how but it give padding for parent instead of child, come from react-native and i feel like it not work like react-native
Please help, here is the codesandbox demo
Demo

add margin to buttons
button {
margin: 0 5px;
}

You can put these buttons into a div and apply grid property on that div.
Like this
<div style={{display:'grid', gridTemplateColumns:'repeat( auto-fit,minmax(250px, 1fr)', gap:'10px'}}>
<button1>1</button1>
<button2>2</button1>
<button3>3</button1>
</div>
Now they are responsive as well.

Related

How to add style on a particular image when hovering in ReactJS?

The problem is that I wanted to add a border to the image and display a Card that contains information when hovering but instead it displays to all the images.
After fetching data from a movie API, I stored the response in the state:
const [movies, setMovies] = useState([])
useEffect(() => {
/**side-effects**/
setMovies(response.data)
},[])
then
let style = {
display: 'none'
};
let imgStyle = {};
if(hover){
style = {
display: 'block'
}
imgStyle = {
border: 1px solid white
}
}
if(movies.length > 1) {
display = (
<div className="MovieContainer">
<h2>Trending this week</h2>
<Carousel>
{movies.map((movie) => {
return (
<>
<img
style={imgStyle}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
className="Images"
key={movie.id}
src={movie.image}
alt={movie.title}
/>
<Card style={style}>{movie.title}</Card>
</>
);
})}
</Carousel>
</div>
);
}
but instead of adding a style to the *hovered* image, it also adds the style to all images.
I also tried using css for the border and it works the way I wanted but I couldn't think of any way for the Cards to show up when hovering
Why do not you do this modification directly in css file, you can just add to your css
img:hover { "2px solid black" }
instead of doing inline styling and using onMouseEnter onMouseLeave

Material-UI style buttons on the right

How do you align buttons on the right using Material-UI's makeStyles function?
I have tried using CSS's margin-right: 0 tag, but there is an error using '-' with makeStyles.
I renamed it as 'marginRight' and it still does not work. Also mr: 0 is not valid either. (Using Material-UI's spacing).
The code is trying to make the UI similar to stackOverflow's title layout.
import React from 'react';
import { makeStyles } from "#material-ui/core/styles";
import { Box, Button } from "#material-ui/core";
const style = makeStyles({
titleItemRight: {
color: 'white',
backgroundColor: 'blue',
top: '50%',
height: 30,
align: 'right',
position: 'relative',
transform: 'translateY(-50%)',
}
});
const App = () => {
const classes = style();
return (
<div>
<Box className={classes.titleBar}>
<Button variant='text' className={classes.titleItemRight}>Sign In</Button>
</Box>
</div>
);
};
Change,
align: 'right'
To,
float: 'right'
So the code would look like,
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import { Box, Button } from "#material-ui/core";
const style = makeStyles({
titleItemRight: {
color: "white",
backgroundColor: "blue",
top: "50%",
height: 30,
float: "right",
position: "relative",
transform: "translateY(-50%)"
}
});
const App = () => {
const classes = style();
return (
<div>
<Box className={classes.titleBar}>
<Button variant="text" className={classes.titleItemRight}>
Sign In
</Button>
</Box>
</div>
);
};
Working Codesandbox
I'd suggest using a flexbox for this or just using the AppBar provided already by material ui
https://material-ui.com/components/app-bar/#app-bar
if you'd still like to use Box, just edit the titleBar styles this way and add a spacer element to seperate elements to far right or far left
const style = makeStyles({
titleBar: {
display: 'flex',
width:'100%',
flexFlow: 'row',
},
spacer: {
flex: '1 1 auto'
}
});
and then your component
<Box className={classes.titleBar}>
<LogoHere/>
<div className={classes.spacer}/>
<Button variant="text">
Sign In
</Button>
</Box>

Adding image to button using Emotion css

I want to style two buttons: Up and Down with an image using emotion css but unable to do so. Currently, I am normally styling my elements within a function. How can I achieve this using emotion css?
I followed https://emotion.sh/docs/introduction but I am unable to implement it the right way.
import up from "../img/up.png";
function PostButton(props) {
let style = {
backgroundRepeat: 'no-repeat',
background: `url(${up})`,
paddingRight: 24,
paddingTop: 26,
paddingLeft: 26,
paddingBottom: 26.6
};
return (
<button style={style} onClick={() => props.handleClick()}>{props.background}</button>
);
}
//I have written similar code for PostButton2
function Post(props) {
return (
<div>
<Up >
<PostButton src={"../images/up.png"} handleClick= .
{props.incrementScore} />
</Up> >
<Down >
<PostButton2 src={"../images/down.png"}
handleClick{props.decrementScore} />
</Down>
</Col>
</Row>
</Container>
</div>
);
}
Assuming that src property holds the background image, I think you need to update background to use the prop like so:
background: `url(${props.src})`,
Use src prop as path to image.
// First way, with css from emotion/react
/** #jsx jsx */
import { jsx, css } from '#emotion/react'
const PostButton = ({ background, handleClick, src }) => (
<button css={css`
background: ${`no-repeat url(${src})`};
padding: 26px 24px 26.6px 26px;
`}
onClick={handleClick}>{background}</button>
)
// Second way, with css from emotion/css
import React from 'react'
import { css } from '#emotion/css'
const PostButton = ({ background, handleClick, src }) => (
<button className={css`
background: ${`no-repeat url(${src})`};
padding: 26px 24px 26.6px 26px;
`}
onClick={handleClick}>{background}</button>
)
// Third way, with css from emotion/css, but pass styles as object
import React from 'react'
import { css } from '#emotion/css'
const PostButton = ({ background, handleClick, src }) => (
<button className={css({
background: `no-repeat url(${src})`,
padding: '26px 24px 26.6px 26px'
})}
onClick={handleClick}>{background}</button>
)

Extending styles with styled-components not working

I'm trying to extend styles for a react component using styled-components but is not working.
AFAIK, I'm doing it the right way, but perhaps I'm missing something...
Here is what I have:
import React from "react";
import styled from "styled-components";
const TextContainer = ({ text }) => {
return <p dangerouslySetInnerHTML={{ __html: text }} />;
};
const Paragraph = styled(TextContainer)`
background: red;
`;
class Home extends React.Component {
render() {
const { t } = this.props;
return <Paragraph text="This is a test" />;
}
}
export default Home;
Of course, the expected result is to have a red background on p, but right now the output looks like this:
Any idea on how to solve this? Probably I'm missing something, but I can't realize what.
Thanks is advance!
As stated in documentation:
The styled method works perfectly on all of your own or any
third-party components, as long as they attach the passed className
prop to a DOM element.
Example
// This could be react-router-dom's Link for example, or any custom component
const Link = ({ className, children }) => (
<a className={className}>
{children}
</a>
);
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`;
render(
<div>
<Link>Unstyled, boring Link</Link>
<br />
<StyledLink>Styled, exciting Link</StyledLink>
</div>
);
Ref: https://www.styled-components.com/docs/basics#styling-any-component
I didn't know that was a way to do it.
I would do:
const Link = styled.a`
..put you css styles here (className styles)
`
const StyledLink = styled(Link) `
color: palevioletred;
font-weight: bold;
`
render(){
return(
<div>
<Link>Unstyled, boring Link</Link>
<br />
<StyledLink>Styled, exciting Link</StyledLink>
</div>
)
}

CSS Positioning elements in a header

So I'm trying to create a navigational menu header and it also includes a logo in it, fairly simple but some of the buttons the left side are inline-block with the logo itself and they appear at the bottom of the logo, to the right of it based on ordering, but at the bottom and im not sure how with css to get them to go to the top of the container or if the roof of their container is just lower that I'm thinking?
import React from 'react';
import {Link} from 'react-router-dom';
import { AuthService } from './backend/client/auth';
import { Paper, Button } from '#material-ui/core';
import { withStyles } from '#material-ui/core/styles';
const styles = theme => ({
container: {
'height': 128,
},
leftnav: {
'display': 'inline-block',
},
rightnav: {
'float': 'right',
},
button: {
'display': 'inline-block',
}
});
class Header extends React.Component {
render() {
const { classes } = this.props;
return (
<Paper className={classes.container}>
<div className={classes.leftnav}>
<Link to="/" className={classes.button}>
<img src="https://imageserver.eveonline.com/Corporation/98523546_128.png" alt="Hole Puncher's Logo"></img>
</Link>
<Button component={Link} to="/">
Home
</Button>
<Button component={Link} to="/store">
Browse
</Button>
<Button component={Link} to="/contact-us">
Contact Us
</Button>
</div>
<div className={classes.rightnav}>
{AuthService.isAuthed()
? <Button component={Link} to="/account/orders">Account</Button>
: ''}
{AuthService.isAuthed()
? <Button component={Link} to="/login">Login</Button>
: <Button onClick={AuthService.logout} component={Link} to="/login"></Button>}
</div>
</Paper>
)
}
}
export default withStyles(styles)(Header);
https://i.imgur.com/OnTjO4l.png
Multiple ways to solve it using CSS. Simplest way is to use vertical-align: top in your button class. I would however recommend you look into display: flex. It's much easier for vertical alignment.
Working JSFiddle here: http://jsfiddle.net/Lhefbudx/
Hope this helps.

Resources