Make onClick on <li> go to another view - reactjs

i'm new on react and i'm doing a project, actually it's a to do list, and i need to make a router that when i click on my item on they send me to details of this item. Here's my actual code. That's my app.js
import React, { Component } from 'react';
import List from './List';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
term: '',
items: []
};
}
onChange = (event) => {
this.setState({ term: event.target.value });
}
onSubmit = (event) => {
event.preventDefault();
this.setState({
term: '',
items: [...this.state.items, this.state.term]
});
}
render() {
return (
<div style={{display: "flex", flexDirection: 'column', alignItems: "center", margin: 5}}>
<form onSubmit={this.onSubmit}>
<input style={{borderRadius: 3, borderColor: "black"}}
value={this.state.term} onChange={this.onChange} />
<button style={{borderRadius: 3, borderColor: "black"}}>
Adicionar</button>
</form>
<List items={this.state.items}/>
</div>
);
}
}
And here my List.js
import React from 'react';
const List = ({ items }) => (
<ul style={{display: "block", listStyleType: "none", backgroundColor: "red"}}>
{
items && items.map((item, index) => <li key={index}>{item}</li>)
}
</ul>
);
export default List;
So i now i will have to use some library to make the route, but first i need to know how i make my itens clickable and when i click they return something that can i redirect to a detail view. Make sense?
And there's a library that you guys recommend to do this job?
Thank you

As i think, you need to use custom links in react As:
1) npm i react-router-dom
2) import {Link} from 'react-router-dom';
3) And finally use <Link to="paste_your_url_here" />
you can also place <Link to='' /> inside of ul, li.

You could add a onClick on each li that redirects to the url you want (implementation may vary based off the lib you choose to handle rooting), but that's not really a good idea since in HTML li are not supposed to be clickable.
What I would do is have a link (again, see with the routing lib - generally it provides a <Link /> component) inside each <li>. This provides better semantic to your code.
Hope this makes sense.
As for a good library... React-router or reach-router are pretty nice!

Related

How to create a horizontal timeline in React

There are two questions already on Stackoverflow:
Create Horizontal Timeline With
React How to create responsive horizontal timeline
None of them have any accepted answer. And also my question is specifically related to react-horizontal-timeline.
I'm creating my personal portfolio and I wish to show my education/college journey.
The author has given the code:
const VALUES = [ /* The date strings go here */ ];
export default class App extends React.Component {
state = { value: 0, previous: 0 };
render() {
return (
<div>
{/* Bounding box for the Timeline */}
<div style={{ width: '60%', height: '100px', margin: '0 auto' }}>
<HorizontalTimeline
index={this.state.value}
indexClick={(index) => {
this.setState({ value: index, previous: this.state.value });
}}
values={ VALUES } />
</div>
<div className='text-center'>
{/* any arbitrary component can go here */}
{this.state.value}
</div>
</div>
);
}
}
Since I'm coming from Angular and MVC frameworks, I didn't understand what this HorizontalTimeline is doing there. Is there anything I need to import? I'm asking this because the code is giving this error:
Line 13:22: 'HorizontalTimeline' is not defined react/jsx-no-undef
Looks like the compiler is not able to recognize HorizontalTimeline.
And also I would like to have it as a separate component for example <MyTimeline> or so. Why would I clutter my App.js. Hope I was able to explain. Please pitch in.
You need to import the component.
Unfortunately the vendor's documentation doesn't include the import statement. Further unfortunately still, the vendor's demo imports it directly from their source code. Which is fine if you're using their source code, but useless if you're installing their npm package.
Unless the IDE can find the import for you (VS Code should be able to, but anything could be preventing that) then best guesses would be:
import HorizontalTimeline from 'react-horizontal-timeline';
or:
import { HorizontalTimeline } from 'react-horizontal-timeline';
Check out this timeline component if you are interested. I think it's better for your need and also has much more clear documentation and a better horizontal mode.
react-chrono
Here is an example of a responsive timeline using the react-chrono component. I have also added some code that will automatically change to the vertical mode which is better for mobile view.
import React from "react";
import { Chrono } from "react-chrono";
class EducationTimeline extends React.Component {
constructor(props) {
super(props);
this.state = { matches: window.matchMedia("(min-width: 768px)").matches };
}
componentDidMount() {
const handler = (e) => this.setState({ matches: e.matches });
window.matchMedia("(min-width: 768px)").addEventListener("change", handler);
}
render() {
const items = [
{
title: "example",
cardTitle: "example",
cardSubtitle: "example",
cardDetailedText: "example",
}
];
return (
<div style={{ width: "500px", height: "400px" }}>
<Chrono
items={items}
mode={this.state.matches ? "HORIZONTAL" : "VERTICAL"}
slideShow={false}
itemWidth={"250"}
hideControls={true}
cardHeight={100}
borderLessCards={true}
theme={{
primary: "#01bf71",
secondary: "#010606",
cardBgColor: "#f7f8fa",
cardForeColor: "#010606",
titleColor: "#fff",
}}
></Chrono>
</div>
);
}
}
export default EducationTimeline;

Material-UI to new hook Reactjs?

All the new examples of how to make reactJS sites are showing examples like
const NavBar = (params) => {
return(
<div>
text
</div>
)
}
export default NavBar;
However material-UI seems to show the following, which is making it really hard for me to understand, how to get the tabs working with the new code format above. How does a constructor work in the new format?
import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
};
export default class TabsExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'a',
};
}
handleChange = (value) => {
this.setState({
value: value,
});
};
render() {
return (
<Tabs
value={this.state.value}
onChange={this.handleChange}
>
<Tab label="Tab A" value="a">
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs are also controllable if you want to programmatically pass them their values.
This allows for more functionality in Tabs such as not
having any Tab selected or assigning them different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="b">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
This is another example of a controllable tab. Remember, if you
use controllable Tabs, you need to give all of your tabs values or else
you wont be able to select them.
</p>
</div>
</Tab>
</Tabs>
);
}
}
EDIT
I found what I needed to do
By using useState I could check what page the use is on and make sure it was the first time the user has entered the site then set a const which then allows me to run another const afterwards to set the tab that needs to be active.
const firstTime = false;
React.useState(() => {
if(!firstTime && window.location.pathname === "/two"){
//console.log('mounted or updated')
firstTime = 1;
}
}
);
const [value, setValue] = React.useState(firstTime);
From MDN:
"The constructor method is a special method for creating and initializing an object created within a class."
The material-ui example is a class component and the new example is a function component. Function components do not use constructors.
Until recently, when the Hooks API was introduced, if a component needed to use State, it had to be a class component, but with Hooks, state can now be manipulated inside of function components. I suggest you read up on this. Here's a good starter:
https://overreacted.io/how-are-function-components-different-from-classes/
Below is a refactored version using a function component and hooks:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Tabs, Tab } from "#material-ui/core";
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400
}
};
const TabsExampleControlled = props => {
const [value, setValue] = useState("a");
return (
<Tabs value={value} onChange={(event, value) => setValue(value)}>
<Tab label="Tab A" value="a">
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs are also controllable if you want to programmatically pass them
their values. This allows for more functionality in Tabs such as not
having any Tab selected or assigning them different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="b">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
This is another example of a controllable tab. Remember, if you use
controllable Tabs, you need to give all of your tabs values or else
you wont be able to select them.
</p>
</div>
</Tab>
</Tabs>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<TabsExampleControlled />, rootElement);
check it out here https://codesandbox.io/s/material-ui-tabs-hooks-wkyzq

Custom Read More in React.js

As you can see this image, "+Las mor" is a "see more" button, which when clicked expands the whole paragraph written above.
I need React code for this to be functional. Any help will be appreciated.
I am also attaching the code upon which this functionality is to be applied.
<section id="section-2">
<h4>Om mig</h4>
<p className="para">
{about}
</p>
</section>
<p style={{color:'#d39176'}}>
<img src={plus1} />
Läs mer
</p>
You probably want a button that toggles the state of expanded text onClick. Upon hitting the button you would set the state to the opposite of what it was. Here's a working example I wrote with React and Reactstrap. I just tested it locally. Here's a video demo of what you will see: https://screencast.com/t/in5clDiyEcUs
import React, { Component } from 'react'
import { Container, Button } from 'reactstrap'
class App extends Component {
constructor(props) {
super(props)
this.state = {
expanded: false //begin with box closed
}
}
//function that takes in expanded and makes it the opposite of what it currently is
showButton = () => {
this.setState({ expanded: !this.state.expanded })
}
render() {
const { expanded } = this.state
return (
<Container style={ { justifyContent: 'center', alignItems: 'center' } }>
<div>Always visable text.</div>
<Button onClick={ this.showButton }>Expand</Button>
{
expanded && //show if expanded is true
<div>Extended Text Here</div>
}
</Container>
)
}
}
export default App

Semantic UI React: how to add a transition to Popup?

I'm building a "hovering" menu, using semantic-ui-react's Popup, and want to add a simple show-hide transition, how it can be done?
this is probably coming in too late for this specific OP, but might be useful for someone else trying to figure same out.
I believe you can use the TransionablePortal as shown in the example. Just for fun, I adapted that example to what I think you are trying to do:
import React, { Component } from 'react'
import { Button, Menu, TransitionablePortal } from 'semantic-ui-react'
export default class TransitionablePortalExamplePortal extends Component {
state = { open: false }
handleOpen = () => this.setState({ open: true })
handleClose = () => this.setState({ open: false })
render() {
const { open } = this.state
return (
<TransitionablePortal
closeOnTriggerClick
onOpen={this.handleOpen}
onClose={this.handleClose}
transition={{animation: "fade left", duration: 500 }}
openOnTriggerClick
trigger={
<Button circular basic
icon="ellipsis vertical"
negative={open}
positive={!open}
/>
}
>
<Menu vertical style={{ right: '1%', position: 'fixed', top: '0%', zIndex: 1000}}>
<Menu.Item>Menu Item 1</Menu.Item>
<Menu.Item>Menu Item 2</Menu.Item>
</Menu>
</TransitionablePortal>
)}}
You should be able to make the transition use onMouseEnter and onMouseLeave if you want same transition to be on hover, instead of on click.
You can find in their official documentation example where you can make custom style for popup
import React from 'react'
import { Button, Popup } from 'semantic-ui-react'
const style = {
borderRadius: 0,
opacity: 0.7,
padding: '2em',
}
const PopupExampleStyle = () => (
<Popup
trigger={<Button icon='eye' />}
content='Popup with a custom style prop'
style={style}
inverted
/>
)
export default PopupExampleStyle
You can try to add transition property here

WithStyles not working in Material UI for React

I have an app using Material UI Beta where I try to style a simple component as follows:
import { MuiThemeProvider } from 'material-ui/styles';
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: 200,
marginRight: theme.spacing.unit,
width: 200,
},
menu: {
width: 200,
},
});
export const CreateJob = (props) => {
const { classes } = props;
let confirmDelete = () => {
const r = window.confirm("Confirm deletion of job");
return r === true;
};
return (
<MuiThemeProvider>
<div>
<form onSubmit={props.isEditting ? props.handleEdit : props.handleSubmit} noValidate autoComplete="off">
<h2>Update job details</h2>
<TextField
error={props.jobIdError !== ''}
helperText={props.jobIdError || "Example: ES10"}
autoFocus
margin="dense"
id="jobId"
label="Job ID"
name="jobid"
fullWidth
onChange={props.handleInputChange('jobId')}
value={props.jobId} />
</form>
</div>
</MultiThemeProvider>
I then use this in my parent component as follows:
<CreateJob open={this.state.open} />
However, this yields the following error:
TypeError: Cannot read property 'classes' of undefined
this.state is not defined in your code. In the example, state is defined as
state = {
name: 'Cat in the Hat',
age: '',
multiline: 'Controlled',
currency: 'EUR',
};
Sorry I'm kinda late with an answer, but I just found this question while searching for another solution.
I'm going to assume you also imported withStyles.
Firstly, you don't need to export both the simple component and the enhanced one:
export const CreateJob = props => {...} // lose the 'export'
export default withStyles(styles)(CreateJob); // only export here
Secondly, a real problem: <MuiThemeProvider> should be placed around your highest component(usually the <App> component that you render in your entry point file), so you can customize the default theme to your liking for the whole app; see their example here. I'm not sure, but this might even solve your problem, since that should have thrown another error like in this issue.
I just hope this helps someone, but I cannot be sure about what your exact problem is without the complete component file.

Resources