React button with image with props - html

now learning react and need to do some similar buttons with different images.
my component:
export default class Button extends Component {
render() {
return (
<button className="header_btn"></button>
)
}
}
How to set image to this button using props? Images saved in local storage

Hi please check this example: Here I pass text and imageUrl as props.
import React from "react";
export default class Button extends React.Component {
render() {
return (
<button className="header_btn">
<img height="15px" width="15px" src={this.props.imageUrl} />
{this.props.text}
</button>
)
}
}
You should use Button Component in your App.js or any other component like below:
<Button text="Click" imageUrl="https://www.tutorialspoint.com/latest/inter-process-communication.png" />

You can apply image on button using background: url('imageAddressInString');
<button style={background: `url(${this.props.imageUrl})`}></button>
and pass imageUrl to Button component in props.
const firstImage = './example.jpg';
<Button imageUrl={firstImage} />

Related

How to change / toggle React state?

I am trying to toggle react state after the button click. After clicking button Work From Office should change to work From Home and vice versa. But it is not working. What am I dong wrong? I am able to change only once. Can we do with if statement? What is simple way?
** React **
import React, { Component } from 'react';
import './ChangeSchedule.css';
class ChangeSchedule extends Component {
constructor(){
super()
this.state = {
// work:'from office'
workFromOffice:true
}
}
changeMyWorkPlace(){
this.setState({
// work:'from Home'
workFromOffice:!this.state.workFromOffice
})
}
render(){
return(
<div>
<div class="schedule change">
<h3>Emplyoee Name: </h3>
<p>Today Pooja is work {this.state.work}</p>
{/* <button class="chageScheduleBtn " onClick = {()=> this.changeMyWorkPlace()}> Change My Schedule </button> */}
<button class="chageScheduleBtn " onClick = {()=> this.workFromOffice() ?'Home': 'Office'}> Change My Schedule </button>
</div>
</div>
)
}
}
export default ChangeSchedule;
You can use a ternary expression to display content for each state.
For example:
{this.state.workFromOffice ? " from Office" : " from Home"}
Now this button should work as you expect:
<button class="chageScheduleBtn" onClick={()=> this.changeMyWorkPlace()}>
Change My Schedule
</button>
See codesandbox for fully working example
You could do it as below. Just change the status when the click happen. And inside the button, use a ternary expression. Like so:
import { Component } from "react";
import "./ChangeSchedule.css";
class ChangeSchedule extends Component {
constructor() {
super();
this.state = {
// work:'from office'
workFromOffice: true,
};
}
changeMyWorkPlace() {
this.setState({
// work:'from Home'
workFromOffice: !this.state.workFromOffice,
});
}
render() {
return (
<div>
<div class="schedule change">
<h3>Emplyoee Name: </h3>
<p>Today Pooja is work {this.state.work}</p>
<button class="chageScheduleBtn " onClick={() => this.workFromOffice()}>
{this.state.workFromOffice ? "Work From Home" : "Work From Office"}
</button>
</div>
</div>
);
}
}
export default ChangeSchedule;
The answer is in the way you're structuring your state. You can make it really simple by just using one entry of the state - workFromOffice. Then, your click handler should care only about changing that state value to the opposite of what was set before. Example:
onClick={() => this.setState({ workFromOffice: !this.state.workFromOffice })}
When the changeMyWorkPlace function created, it captures your initial state and uses it everytime you run the function so only works once. You should instruct react to use up to date state.
try this way.
changeMyWorkPlace(){
this.setState((previousState) => ({
// work:'from Home'
workFromOffice:!previousState.workFromOffice
}))
}

how can I add props inside class in html which already exists

I want to add a class from another file as a prop, but I am not able to do it.
file 1
import React from 'react'
const Button = (props) => {
return (
<div>
<button class={"btn btn-primary" props.classes } type="submit" >{props.name}</button>
</div>
)
}
export default Button
file 2:
<Button name="Sign Up" classes="me-sm-0"></Button>
You just have to pass the desired className in the props just like below:
const Button = (props) => {
return (
<div>
<button className={`btn btn-primary ${props.className}`} type="submit" >{props.name}</button>
</div>
)
}
And this will be the Component used:
<Button name="Sign Up" className="me-sm-0"></Button>
I have read your article carefully.
I think your attempt to pass classes as props of the Button component worked really well.
If there is one disappointment, the syntax of react jsx is wrong.
In react jsx, the class property of html should be written as className.
And use ...${regexp}, one of the new features in es6.
I attach the code below.
--App.js
import React from 'react';
import './style.css';
import Button from './Button';
export default function App() {
return (
<div>
<Button name="Sign Up" classes="me-sm-0" />
</div>
);
}
--Button.js
import React from 'react';
export default function Button(props) {
return (
<div>
<button className={`btn btn-primary ${props.classes}`} type="submit">
{props.name}
</button>
</div>
);
}

React Chakra UI modal only shows overlay

I'm using Chakra UI in React with Typescript and having such a weird issue I trying to implement Modal with the following code in modal.tsx file.
import {
useDisclosure,
Button,
Modal,
ModalOverlay,
ModalContent,
ModalHeader,
ModalCloseButton,
ModalBody,
ModalFooter,
} from "#chakra-ui/react";
export default function CustomModal() {
const { isOpen, onOpen, onClose } = useDisclosure();
return (
<>
<Button onClick={onOpen}>Open Modal</Button>
<Modal closeOnOverlayClick={false} isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Create your account</ModalHeader>
<ModalCloseButton />
<ModalBody pb={6}></ModalBody>
<ModalFooter>
<Button colorScheme="blue" mr={3}>
Save
</Button>
<Button onClick={onClose}>Cancel</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
);
}
once i click on Open Modal button it simply shows the overlay without actual content of the modal.
I tried to reproduce your problem and found that - For Chakra UI to work correctly, you need to set up the ChakraProvider at the root of your application.
import * as React from "react"
// 1. import `ChakraProvider` component
import { ChakraProvider } from "#chakra-ui/react"
function App({ Component }) {
// 2. Use at the root of your app
return (
<ChakraProvider>
<Component />
</ChakraProvider>
)}
Here is the running code sandbox link of your problem.
In App.js I wrapped the application in <ChakraProvider>.
Hope it works for you.
First Check You Wrappped Your App With ChakraProvider If Provided

Show dialog in React - Material UI

I am learning ReactJS. I would like to display dialog when someone clicks on the icon.
Here is the code:
import React, { Component } from 'react';
import { GridList, GridTile } from 'material-ui/GridList';
import FlatButton from 'material-ui/FlatButton';
import Info from 'material-ui/svg-icons/action/info';
import { fullWhite } from 'material-ui/styles/colors';
import Dialog from 'material-ui/Dialog';
import RaisedButton from 'material-ui/RaisedButton';
(... class stuff, handleClose, handleOpen etc.)
showDialoga() {
const actions = [
<FlatButton
label="Cancel"
primary
onClick={this.handleClose}
/>,
<FlatButton
label="Submit"
primary
keyboardFocused
onClick={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Dialog" onClick={this.handleOpen} />
<Dialog
title="Dialog With Actions"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
The actions in this window were passed in as an array of React objects.
</Dialog>
</div>
);
}
render() {
console.log(this.props);
return (
<div style={styles.root}>
<GridList
cellHeight={180}
style={styles.gridList}
padding={10}
>
{this.props.movieData.map(tile => (
<GridTile
key={tile.original_image}
title={tile.title}
actionIcon={<FlatButton
icon={<Info color={fullWhite} />}
style={style}
onClick={() => this.showDialoga()}
/>}
>
<img src={tile.original_image} />
</GridTile>
))}
</GridList>
</div>
);
}
}
I am able to pass other function like () => console.log('I am clicked') to onClick although I am not able to pass that showDialoga().
Any idea what is the problem?
I do not believe that's how you are supposed to use dialog.
Instead of passing return of React component on click, try setting the dialog opened state to be true/false. Also do not forget to bind this to the class level if you are using functions to render different components that has event listeners.

Materialize carousel-item not inheriting default properties

Able to fetch the data from API.
But the problem is when I try to map the carousel-item inside class carousel.
The properties are not being inherited.
When I inspect, I see there are carousel-item inside carousel, but they are not having the default properties.
This is my Carousel Class
class Carousel extends Component {
constructor(props){
super(props);
this.state = { albums: [] };
}
componentWillMount() {
axios.get('http://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({albums: response.data}));
}
renderAlbums(){
return this.state.albums.map(album =>
<Card song={album.title} singer={album.artist} src={album.thumbnail_image}/>
);
}
render() {
return (
<div className="carousel center">
{this.renderAlbums()}
</div>
);
}
}
export default Carousel;
This is my Card Component
import React, { Component } from 'react';
import '../../App.css';
class Card extends Component {
render() {
return (
<div className="carousel-item center">
<div className="card z-depth-4">
<div>
<img src={this.props.src} className="responsive-img"/>
</div>
<p>{this.props.song}</p>
<div className="singer">{this.props.singer}</div>
</div>
</div>
);
}
}
export default Card;
Please suggest if there is any other way, to import it.
Already have initialised carousel and it's working if I try the Materialize Example
Try performing your API call in componentDidMount instead of componentWillMount.
The latter is called before the initial render, and thus, if your API call returns before the component finishes mounting, the setState statement will not cause a re-render.
With the former, setting the state will always cause a re-render to occur. React documentation recommends initiating data requests from remote endpoints from componentDidMount. See here.