Class extends using functions inside render? - javascript

I'm looking for a way to reduce code redundancy through class extending/inheritance on JavaScript/react.js.
For example, I want to have two types of UserCard components, that both represent a user's info, but one is for detailed (normal) view, other one is for list (mini) view. (e.g. imagine the normal one is something you may see on /user/:id and mini one is on /users)
Specifically, I wanted to have, for the normal ones, 1. its username and bio, icon, etc 2. its latset posts 3. extra actions (e.g. following/DM), and for the mini ones, exclude the 2. and 3. from the normal UserCard.
To implement the above model I thought I should use a JS extends or something (I'm not very familiar with extends), so basically I tried something similar to the following.
I know the following doesn't work, but I really don't have a good idea to how. What should I do with the issue? Thanks.
class UserCardBase extends Component {
constructor(props) {
super(props);
this.state = {
page_size: 3,
newly_order: true,
};
};
componentDidMount() {
{/* gets the user data */ }
axios.get(`/api/users/${this.props.id}`)
.then((response) => { this.setState({ user: response.data, updated: true, }); })
.catch((error) => { console.log(error); toast.error(() => <>failed.</>); });
};
render() {
const renderBlogcards = (props) => {
{/* renders blogcards */ }
return this.state.posts?.map((post, i) => <BlogCard key={i} data={post} />)
}
const extraActions = (props) => {
{/* enables follow/message */ }
return <div className="card__user-actions">
<button className="card__user-actions-follow">Follow</button>
<button className="card__user-actions-message">Message</button>
</div>
}
// mini sized usercard
const ContentMini = (props) => (
<>
<div className="__user_card">
<div className="card" >
<main className="card__user">
<img src={this.state.user?.userprofile.avatar} alt="" className="card__user-image"></img>
<div className="card__user-info">
<Link to={`/user/${this.state.user?.id}`}><h2 className="card__user-info__name">#{this.state.user?.username}</h2></Link>
<p className="card__user-info__desc">{this.state.user?.userbio.bio}</p>
</div>
</main>
</div>
</div>
</>
)
// default sized usercard
const Content = (props) => (
<>
<div className="__user_card">
<div className="card" >
<main className="card__user">
<img src={this.state.user?.userprofile.avatar} alt="" className="card__user-image"></img>
<div className="card__user-info">
<Link to={`/user/${this.state.user?.id}`}><h2 className="card__user-info__name">#{this.state.user?.username}</h2></Link>
<p className="card__user-info__desc">{this.state.user?.userbio.bio}</p>
</div>
<extraActions />
</main>
<renderBlogcards />
</div>
</div>
</>
)
return (
<>
{/* by default, uses the mini usercard */ }
<ContentMini />
</>
);
}
}
class UserCard extends UserCardBase {
constructor(props) {
super(props);
};
render() {
return (
<>
{/* assume trying overrides the render so uses the normal usercard replacing the mini */ }
<Content />
</>
)
}
}

Related

What is weird "/.$" or ".$" in the react key name?

I need to put the change children with some element like div in react component. and I found lot of way to do that.
The problem is when I create a holder element over the child and give right key to the holder but the react added some weird character to the key and change my key.
I want to use react-grid-layout but the keys should be the same of the layout config props. so, I need to react stop changing the keys.
Here is my code:
class Main extends React.Component {
render() {
const { index, children } = this.props;
// Sample1: /.$
const childWithHolders1 = React.Children.map(children, child => (
<div key={"holder" + child.key}>
holder key: {"holder" + child.key}
</div>
));
const realReactKeys1 = childWithHolders1.map(divComp => divComp.key + "\n");
// Sample2: .$ (just pass number to the key)
const childWithHolders2 = React.Children.map(children, child => (
<div key={child.key}>
holder key: {child.key}
</div>
));
const realReactKeys2 = childWithHolders2.map(divComp => divComp.key + "\n");
return (
<div>
<h2>Sample 1</h2>
{childWithHolders1}
<br />
<h3>The Real React Keys: </h3>
<pre>{realReactKeys1}</pre>
<br /><h2>Sample 2</h2>
{childWithHolders2}
<br />
<h3>The Real React Keys: </h3>
<pre>{realReactKeys2}</pre>
</div>
);
}
}
class Child extends React.Component {
render() {
const { index } = this.props;
return (
<p>Child Index: {index}</p>
)
}
}
class App extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<h2>What is weird "/.$" or ".$" in the react key name ???</h2>
<Main>
<Child key="1" index="1" />
<Child key="2" index="1" />
<Child key="3" index="1" />
</Main>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

React/Gatsby component interaction (lifting state up) with components in MDX files

I use Gatsby with the MDX plugin. So I can use React components in markdown. That's fine.
I have components, talking to each other. To do this I use the Lifting State Up Pattern. That's fine.
Here is a basic Counter example, to show my proof of concept code.
import React from "react"
export class Counter extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0 }
this.handleCounterUpdate = this.handleCounterUpdate.bind(this)
}
handleCounterUpdate() {
this.setState({ count: this.state.count + 1 })
}
render() {
const children = React.Children.map(this.props.children, child => {
const additionalProps = {}
additionalProps.count = this.state.count
additionalProps.handleCounterUpdate = this.handleCounterUpdate
return React.cloneElement(child, additionalProps)
})
return <div>{children}</div>
}
}
export function Display({ count }) {
return <h2>Current counter is: {count}</h2>
}
export function UpdateButton({ handleCounterUpdate }) {
return <button onClick={handleCounterUpdate}>Increment couter by one</button>
}
With this setup, one can use the components like this
<Counter>
<Display />
<UpdateButton />
</Counter>
or even like this
<Counter>
<Display />
<UpdateButton />
<Display />
<Display />
</Counter>
That's fine.
In real-world, the enclosing Counter component (state holder), will be something like a Layout component. The <Layout> is used in a template and renders the MDX pages. This looks like that:
<SiteLayout>
<SEO title={title} description={description} />
<TopNavigation />
<Display /> // The state holder is <SiteLayout>, not <Counter>
<Breadcrumb location={location} />
<MDXRenderer>{page.body}</MDXRenderer> // The rendered MDX
</SiteLayout>
The <UpdateButton> (in real-world something like <AddToCartButton>) is on the MDX page and not anymore a direct child from the <Layout> component.
The pattern does not work anymore.
How can I resolve this?
Thanks all
import React from "react"
// This is a proof of concept (POC) for intercomponent communication using
// React Context
//
// In the real world Gatsby/React app we use a kind of cart summary component
// at top right of each page. The site consists of thousands of pages with detailed
// product information and a blog. Users have the possibility to add products directly
// from product information pages and blog posts. Posts and pages are written in
// MDX (Mardown + React components). All <AddToCartButtons> reside in MDX files.
//
// This code uses a "increment counter button" (= add to cart button) and a
// display (= cart summary) as POC
//
// More information at
// https://reactjs.org/docs/context.html#updating-context-from-a-nested-component
export const CounterContext = React.createContext()
// The <Layout> component handles all business logic. Thats fine. We have
// very few app features.
export class Layout extends React.Component {
constructor(props) {
super(props)
this.handleCounterUpdate = this.handleCounterUpdate.bind(this)
this.state = { count: 0, increment: this.handleCounterUpdate }
}
handleCounterUpdate() {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<div style={{ backgroundColor: "silver", padding: "20px" }}>
<CounterContext.Provider value={this.state}>
{this.props.children}
</CounterContext.Provider>
</div>
)
}
}
export class UpdateButton extends React.Component {
static contextType = CounterContext
render() {
const count = this.context.count
const increment = this.context.increment
return (
<button onClick={increment}>
Increment counter (current value: {count})
</button>
)
}
}
export class Display extends React.Component {
static contextType = CounterContext
render() {
return (
<div
style={{
backgroundColor: "white",
padding: "10px",
margin: "10px 0 0 0"
}}
>
<div>I'm Display. I know the count: {this.context.count}</div>
<div>{this.props.children}</div>
</div>
)
}
}
// Function components use <CounterContext.Consumer>. Class components
// use static contextType = CounterContext
export function AChild() {
return (
<CounterContext.Consumer>
{context => (
<span>
I'm a child of Display. I know the count too: {context.count}
</span>
)}
</CounterContext.Consumer>
)
}
Use it like this
<Layout>
<Display>
<AChild />
</Display>
// UpdateButton inside MDX files
<MDXRenderer>{page.body}</MDXRenderer>
// Or elsewhere
<UpdateButton />
</Layout>

What is the correct way to select one of many child elements in React?

I have a small part of my new React app which contains a block of text, AllLines, split into line-by-line components called Line. I want to make it work so that when one line is clicked, it will be selected and editable and all other lines will appear as <p> elements. How can I best manage the state here such that only one of the lines is selected at any given time? The part I am struggling with is determining which Line element has been clicked in a way that the parent can change its state.
I know ways that I can make this work, but I'm relatively new to React and trying to get my head into 'thinking in React' by doing things properly so I'm keen to find out what is the best practice in this situation.
class AllLines extends Component {
state = {
selectedLine: 0,
lines: []
};
handleClick = (e) => {
console.log("click");
};
render() {
return (
<Container>
{
this.state.lines.map((subtitle, index) => {
if (index === this.state.selectedLine) {
return (
<div id={"text-line-" + index}>
<TranscriptionLine
lineContent={subtitle.text}
selected={true}
/>
</div>
)
}
return (
<div id={"text-line-" + index}>
<Line
lineContent={subtitle.text}
handleClick={this.handleClick}
/>
</div>
)
})
}
</Container>
);
}
}
class Line extends Component {
render() {
if (this.props.selected === true) {
return (
<input type="text" value={this.props.lineContent} />
)
}
return (
<p id={} onClick={this.props.handleClick}>{this.props.lineContent}</p>
);
}
}
In your case, there is no really simpler way. State of current selected Line is "above" line collection (parent), which is correct (for case where siblings need to know).
However, you could simplify your code a lot:
<Container>
{this.state.lines.map((subtitle, index) => (
<div id={"text-line-" + index}>
<Line
handleClick={this.handleClick}
lineContent={subtitle.text}
selected={index === this.state.selectedLine}
/>
</div>
))}
</Container>
and for Line component, it is good practice to use functional component, since it is stateless and even doesn't use any lifecycle method.
Edit: Added missing close bracket
'Thinking in React' you would want to give up your habit to grab DOM elements by their unique id ;)
From what I see, there're few parts missing from your codebase:
smart click handler that will keep only one line selected at a time
edit line handler that will stick to the callback that will modify line contents within parent state
preferably two separate components for the line capable of editing and line being actually edited as those behave in a different way and appear as different DOM elements
To wrap up the above, I'd slightly rephrase your code into the following:
const { Component } = React,
{ render } = ReactDOM
const linesData = Array.from(
{length:10},
(_,i) => `There goes the line number ${i}`
)
class Line extends Component {
render(){
return (
<p onClick={this.props.onSelect}>{this.props.lineContent}</p>
)
}
}
class TranscriptionLine extends Component {
constructor(props){
super(props)
this.state = {
content: this.props.lineContent
}
this.onEdit = this.onEdit.bind(this)
}
onEdit(value){
this.setState({content:value})
this.props.pushEditUp(value, this.props.lineIndex)
}
render(){
return (
<input
style={{width:200}}
value={this.state.content}
onChange={({target:{value}}) => this.onEdit(value)}
/>
)
}
}
class AllLines extends Component {
constructor (props) {
super(props)
this.state = {
selectedLine: null,
lines: this.props.lines
}
this.handleSelect = this.handleSelect.bind(this)
this.handleEdit = this.handleEdit.bind(this)
}
handleSelect(idx){
this.setState({selectedLine:idx})
}
handleEdit(newLineValue, lineIdx){
const linesShallowCopy = [...this.state.lines]
linesShallowCopy.splice(lineIdx,1,newLineValue)
this.setState({
lines: linesShallowCopy
})
}
render() {
return (
<div>
{
this.state.lines.map((text, index) => {
if(index === this.state.selectedLine) {
return (
<TranscriptionLine
lineContent={text}
lineIndex={index}
pushEditUp={this.handleEdit}
/>
)
}
else
return (
<Line
lineContent={text}
lineIndex={index}
onSelect={() => this.handleSelect(index)}
/>
)
})
}
</div>
)
}
}
render (
<AllLines lines={linesData} />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

React sibling communication with ONLY access to parent

I am trying to create something similar to React Bootstrap's dropdown component. My starting skeleton is something like the following:
import React from 'react';
const DropDown = props => {
return <div className="dropdown-container">{props.children}</div>;
};
const DropDownToggle = props => {
return <div className="dropdown-toggle">{props.children}</div>;
};
const DropDownContent = props => {
return <div className="dropdown-content">{props.children}</div>;
};
export { DropDown, DropDownToggle, DropDownContent };
These components would be used like this:
<DropDown>
<DropDownToggle>
{/*
The content inside here should be customizable so the user of
these components can specify whatever they want for the toggle
*/}
<button type="button">
my button
</button>
</DropDownToggle>
<DropDownContent>
{/*
The content inside here should be customizable so the user of
these components can specify whatever they want for the content of
the dropdown
*/}
<ContentComponent/>
</DropDownContent>
</DropDown>
Is there a way I can communicate between the two children components (DropDownContent and DropDownToggle)? I have access to the parent component and it just receives and displays the children so far, but I would like to somehow communicate between the children so that the user can click on the toggle to open/close the content. I don't want to use redux.
Thank you in advance!
EDIT
I ended up going with the method that #Train suggested in his/her comment below. I was originally hoping for the ability to nest components manually, but what was most important to me was having the state be self-contained in the parent component. Being able to define the toggle button's HTML as well as the content's HTML was also a requirement. My final implementation allows for both of these things and looks something like this:
import React from 'react';
import PropTypes from 'prop-types';
export class Dropdown extends React.Component {
state = {
isOpen: false,
};
onDropDownToggleClick = () => {
this.setState({ isOpen: !this.state.isOpen });
};
render() {
let contentClasses = 'dropdown-content';
if (this.state.isOpen) {
contentClasses += ' show';
}
return (
<div className="dropdown-container">
<div className="dropdown-toggle" onClick={this.onDropDownToggleClick}>
{this.props.toggle}
</div>
<div className={contentClasses}>{this.props.content}</div>
</div>
);
}
}
Dropdown.propTypes = {
toggle: PropTypes.oneOfType([PropTypes.string, PropTypes.element]).isRequired,
content: PropTypes.oneOfType([PropTypes.string, PropTypes.element])
.isRequired,
};
export default Dropdown;
to use it:
const dropDownToggle = (
<button type="button">
Dropdown
</button>
);
const dropDownContent = 'content';
<DropDown
toggle={dropDownToggle}
content={dropDownContent}
/>
For something like toggling content you can use composition instead of inheritance to pass data around.
From the example of Facebook
This is done with props.children property.
function Dialog(props) {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
{props.title}
</h1>
<p className="Dialog-message">
{props.message}
</p>
{props.children}
</FancyBorder>
);
}
class SignUpDialog extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSignUp = this.handleSignUp.bind(this);
this.state = {login: ''};
}
render() {
return (
<Dialog title="Mars Exploration Program"
message="How should we refer to you?">
<input value={this.state.login}
onChange={this.handleChange} />
<button onClick={this.handleSignUp}>
Sign Me Up!
</button>
</Dialog>
);
}
handleChange(e) {
this.setState({login: e.target.value});
}
handleSignUp() {
alert(`Welcome aboard, ${this.state.login}!`);
}
}
In the render() I am rendering the Dialog component and passing in the props.
the props are .children and the custom props title, message
This lets us pass child elements directly into the output we can even add components from other classes as I did with the SignUpDialog.
Did you have something like this in mind?
const actionTypes = {
TOGGLE: "TOGGLE"
};
const notRedux = {
actionHandlers: Object.keys(actionTypes).reduce(
(acc, val) => ({ [val]: [], ...acc }),
{}
),
dispatchAction(actionType, data) {
this.actionHandlers[actionType].forEach(handler => handler(data));
},
onAction(actionType, actionHandler) {
this.actionHandlers[actionType].push(actionHandler);
}
};
const DropDown = ({ children }) => {
return <div className="dropdown-container">{children}</div>;
};
const DropDownToggle = () => {
const onClick = () =>
notRedux.dispatchAction(actionTypes.TOGGLE, "oh hi Mark");
return (
<div className="dropdown-toggle">
<button type="button" onClick={onClick}>
my button
</button>
</div>
);
};
const DropDownContent = props => {
notRedux.onAction(actionTypes.TOGGLE, data =>
alert(`DropDownToggle said ${data} //DropDownContent`)
);
return <div className="dropdown-content">{props.children}</div>;
};
const App = () => (
<DropDown>
<DropDownToggle></DropDownToggle>
<DropDownContent>
<span>Content goes here</span>
</DropDownContent>
</DropDown>
);
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></app>

Moving data between react components

So I'm trying to break the component on my App.js into a smaller component, that being my Sidebar.js. I took a small section of the code and put it in its own Sidebar.js file but no matter what I've tried, I cant call my function getNotesRows() from App.js without it being unable to find it or this.states.notes being undefined.
I just want it to send the code back and forth. This is a demo app, so I know it's not the most practical.
import React, { Component } from "react";
import classNames from "classnames";
import logo from "./logo.svg";
import checkMark from "./check-mark.svg";
import "./App.css";
import Sidebar from "./components/Sidebar.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
notes: [],
currentNoteIndex: 0
};
this.markAsRead = this.markAsRead.bind(this);
this.selectNote = this.selectNote.bind(this);
console.log("Test started 2.25.19 19:23");
}
componentWillMount() {
fetch('/notes')
.then(response => response.json())
.then(
notes => {
this.setState({
notes: notes,
currentNoteIndex: 0
})
}
)
.catch(
error => {
console.log('Ooops!');
console.log(error);
}
);
}
markAsRead() {
this.setState(currentState => {
let marked = {
...currentState.notes[currentState.currentNoteIndex],
read: true
};
let notes = [...currentState.notes];
notes[currentState.currentNoteIndex] = marked;
return { ...currentState, notes };
});
}
selectNote(e) {
this.setState({ currentNoteIndex: parseInt(e.currentTarget.id, 10) });
}
getTotalUnread() {
let unreadArray = this.state.notes.filter(note => {
return note.read === false;
})
return unreadArray.length;
}
getNotesRows() {
return this.props.notes.map(note => (
<div
key={note.subject}
className={classNames("NotesSidebarItem", {
selected:
this.props.notes.indexOf(note) === this.props.currentNoteIndex
})}
onClick={this.selectNote}
id={this.props.notes.indexOf(note)}
>
<h4 className="NotesSidebarItem-title">{note.subject}</h4>
{note.read && <img alt="Check Mark" src={checkMark} />}
</div>
));
}
// TODO this component should be broken into separate components.
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Notes Viewer Test App</h1>
<div>
Unread:
<span className="App-title-unread-count">
{this.getTotalUnread()}
</span>
</div>
</header>
<div className="Container">
<Sidebar />
<section className="NoteDetails">
{this.state.notes.length > 0 && (
<h3 className="NoteDetails-title">
{this.state.notes[this.state.currentNoteIndex].subject}
</h3>
)}
{this.state.notes.length > 0 && (
<p className="NoteDetails-subject">
{this.state.notes[this.state.currentNoteIndex].body}
</p>
)}
{this.state.notes.length > 0 && (
<button onClick={this.markAsRead}>Mark as read</button>
)}
{this.state.notes.length <= 0 && (
<p>
No Notes!
</p>
)}
</section>
</div>
</div>
);
}
}
export default App;
Above is my App.js
and below is the Sidebar.js that I'm trying to create
import React, { Component } from "react";
import "../App.css";
import App from "../App.js";
class Sidebar extends React.Component{
constructor(props) {
super(props);
}
render(){
return (
<section className="NotesSidebar">
<h2 className="NotesSidebar-title">Available Notes:</h2>
<div className="NotesSidebar-list">{App.getNotesRows()}</div>
</section>
)}}
export default Sidebar;
You cannot access a method like that. You need to pass the method as a prop and use it in the child.
<Sidebar getNotesRows={this.getNotesRows} />
and in Sidebar use
<div className="NotesSidebar-list">{this.props.getNotesRows()}</div>
In your sidebar, you're trying to call getNotesRows() from App, but Sidebar doesn't need access to app (you shouldn't have to import App in Sidebar.js). Instead, you should pass the function from App to your Sidebar component, and reference it from Sidebar's props.
In App.js, you'll need to bind getNotesRows and pass it to sidebar.:
<Sidebar getNotesRows={ this.getNotesRows } />
Then in Sidebar.js, you'll need to reference getNotesRows in your render method:
render() {
const notes = this.props.getNotesRows();
return (
<section className="NotesSidebar">
<h2 className="NotesSidebar-title">Available Notes:</h2>
<div className="NotesSidebar-list">{ notes }</div>
</section>
);
}
It seems like the problem here is that you are trying to use a class function as a static property, to put it simply, you have not initialized the App class when you import it into your sidebar(?), thus no static function was found on your App class so you can call App.getNotesRows() maybe you should re-think your components and separate them in container-components using a Composition Based Programming approach instead of OO approach.

Categories