Stone
Stone

Reputation: 291

Can I render piece of a stateful component in react?

Is there any API that allow us to write code something like this:

const MyComponents = () => {
    const [number, setNumber] = useState(0);

    return {
        Btn: <Button onPress={() => setNumber(number + 1)}>
            {number}
        </Button>,
        Log: <p>{number}</p>
    }
}

const Parent = () => <>
    <div ...>
       <MyComponents.Btn/>
        ...
        ...
    </div>
    <MyComponents.Log/>
</>

Some kind of ability to group some Component.And render them in different places...

Upvotes: 0

Views: 41

Answers (1)

JLRishe
JLRishe

Reputation: 101690

Seems like this would be better achieved by using a Context.

E.g.

const { createContext, useState, useContext } = React;

const CountContext = createContext();

const CountContainer = ({ children }) => {
    const [number, setNumber] = useState(0);

    return <CountContext.Provider value={{ number, setNumber }}>
        {children}
    </CountContext.Provider>
};

const CountButton = () => {
    const { number, setNumber } = useContext(CountContext);

    return <button onClick={() => setNumber((c) => c + 1)}>
        {number}
    </button>;
};

const CountLog = () => {
    const { number } = useContext(CountContext);

    return <p>{number}</p>;
};


const SomeCountButtons = () => <div><CountButton /><CountButton /></div>;

const App = () => (<div>
    <CountContainer>
        <CountButton />
        <CountLog />
    </CountContainer>
    <CountContainer>
        <SomeCountButtons />
        <CountLog />
    </CountContainer>
</div>);

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
    
<div id="app"></div>

Then any <CountButton>s or <CountLog>s that occur anywhere within the same <CountContainer> will be able to share their state.

Upvotes: 2

Related Questions